最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - remove values from a string - Stack Overflow

programmeradmin3浏览0评论

Does anyone know how I would remove all leading zeros from a string.

var str = 000890

The string value changes all the time so I need it to be able to remove all 0s before a number greater than 0. So in the example above it needs to remove the first three 0s. So the result would be 890

Does anyone know how I would remove all leading zeros from a string.

var str = 000890

The string value changes all the time so I need it to be able to remove all 0s before a number greater than 0. So in the example above it needs to remove the first three 0s. So the result would be 890

Share Improve this question edited Dec 16, 2011 at 20:28 Joseph Stine 1,0221 gold badge12 silver badges23 bronze badges asked Dec 16, 2011 at 20:05 ChapsterjChapsterj 6,62521 gold badges73 silver badges124 bronze badges
Add a ment  | 

9 Answers 9

Reset to default 9

It looks like we each have our own ways of doing this. I've created a test on jsperf., but the results are showing

String(Number('000890'));

is the quickest (on google chrome).


Here are the numbers for the updated test based on @BenLee's ment for Firefox, IE, and Chrome.

See: this question

var resultString = str.replace(/^[0]+/g,"");
var resultString = str.replace(/^[0]+/g,"");

I think a function like this should work

   function replacezeros(text){    
      var newText = text.replace(/^[0]+/g,"");
      return newText;
}

If it needs to stay as a string, cast it to a number, and cast it back to a string:

var num = '000123';
num = String(Number(num));
console.log(num);

You could also use the shorthand num = ''+(+num);. Although, I find the first form to be more readable.

parseInt('00890', 10); // returns 890
// or
Number('00890'); // returns 890 

If your problem really is as you defined it, then go with one of the regex-based answers others have posted.

If the problem is just that you have a zero-padded integer in your string and need to manipulate the integer value without the zero-padding, you can just convert it to an integer like this:

parseInt("000890", 10) # => 890

Note that the result here is the integer 890 not the string "890". Also note that the radix 10 is required here because the string starts with a zero.

return str.replace(/^0+(.)/, '$1'));

That is: replace maximum number of leading zeros followed by any single character (which won't be a zero), with that single character. This is necessary so as not to swallow up a single "0"

you can simply do that removing the quotation marks.

var str = 000890;
//890
var str = "000890";
//000890
发布评论

评论列表(0)

  1. 暂无评论