3

I have many strings like this:

0001, 0002, ..., 0010, 0011, ..., 0100, 0101,...

I would like these to become like this:

1, 2, ..., 10, 11, ..., 100, 101, ...

So I would like to remove all the 0 chars before a different char is present. I tried with

.replace(/0/g, '') 

But of course then it also removes the 0 chars after. Therefore for example 0010 becomes 1 instead of 10. Can you please help me?

Amareesh
  • 368
  • 2
  • 5
  • 19
ayasha
  • 1,221
  • 5
  • 27
  • 46

5 Answers5

3

You can do

.replace(/\d+/g, function(v){ return +v })
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
2

This is the shortes Solution

"0001".replace(/^0+/,""); // => 1 
...
// Tested on Win7 Chrome 44+

^ ... starting of the String 0+ ... At least one 0

P.s.: test Regex on pages likes: https://regex101.com/ or https://www.debuggex.com

Update 1:

For one long String

 "0001, 0002, 0010, 0011, 0100, 0101".replace(/(^|\s)0+/g,"") // => 1, 2, 10, 11, 100, 101
 // Tested on Win7 Chrome 44+

Examples:

//  short Strings
var values = ['0001', '0002','0010', '0011','0100','0101'];
for(var idx in values){
  document.write(values[idx] + " -> "+values[idx].replace(/^0+/,"") + "<br/>");
}

// one long String 
document.write("0001, 0002, 0010, 0011, 0100, 0101".replace(/(^|\s)0+/g,""));
winner_joiner
  • 12,173
  • 4
  • 36
  • 61
1

Use regex as /(^|,\s*)0+/g it will select 0's at beginning or followed by , and space

document.write('0001, 0002, ..., 0010, 0011, ..., 0100, 0101,...'.replace(/(^|,\s*)0+/g,'$1'))

Explanation :

(^|,\s*)0+

Regular expression visualization

Debuggex Demo

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
1

Previously answered here.

.replace(/^0+(?!$)/, '')

Functionally the same as winner_joiner's answer, with the exception that this particular regex won't return a completely empty string should the input consist entirely of zeroes.

Community
  • 1
  • 1
0

var text='00101'; var result=parseInt(text);