Chapsterj
Chapsterj

Reputation: 6625

remove values from a string

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

Upvotes: 3

Views: 171

Answers (9)

JesseBuesking
JesseBuesking

Reputation: 6586

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

String(Number('000890'));

is the quickest (on google chrome).

enter image description here


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

enter image description here

Upvotes: 9

Ben Lee
Ben Lee

Reputation: 53319

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.

Upvotes: 2

smendola
smendola

Reputation: 2311

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"

Upvotes: 1

Troy Watt
Troy Watt

Reputation: 888

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

Upvotes: 2

zzzzBov
zzzzBov

Reputation: 179046

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.

Upvotes: 2

Eduardo Moniz
Eduardo Moniz

Reputation: 2115

you can simply do that removing the quotation marks.

var str = 000890;
//890
var str = "000890";
//000890

Upvotes: -1

Dominic Green
Dominic Green

Reputation: 10258

I think a function like this should work

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

Upvotes: 2

Anders
Anders

Reputation: 15397

See: this question

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

Upvotes: 5

Zoltan Toth
Zoltan Toth

Reputation: 47667

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

Upvotes: 4

Related Questions