1

I have a text box where users can enter only numbers separated by commas.

For instance users can enter only 10,11,13,20 and so on. but they shouldn enter as 010,011,00013,020.

I tried this one but to no avail

    newValue.replace(/[^\d,]+/g, '').replace(/^0+/, '').replace(/,,/g, ',');

This restricts only the starting zero,limits the space and numbers only but in-between zeros are not restricted.

Is there any regular expression to replace all the leading zeros in the string above to make it as 10,11,13,20 allowing only one comma in between

Jovial Andree
  • 73
  • 1
  • 10

2 Answers2

4

Very easy, match sequences of digits, for each match remove the 0es on the left:

replace(/0*([0-9]+)/g, "$1")

Sample and explanation here: http://regex101.com/r/xW6dC2

Edit (disallow single digit 0es):

replace(/0+,?|0*([0-9]+,?)/g, "$1")

http://regex101.com/r/qT7zU1

guido
  • 18,864
  • 6
  • 70
  • 95
2

Using capturing group:

'010,011,00013,020'.replace(/(^|,)0+/g, '$1')
// => "10,11,13,20"

UPDATE

To avoid remove all 0 from 0000 or 0, use following: (negative lookahead assertion)

'00'.replace(/(^|,)0+(?!$)/g, '$1')
// => "0"

Using word boundary (\b):

'010,011,00013,020'.replace(/\b0+(?!$)/g, '')
// => "10,11,13,20"
'000'.replace(/\b0+(?!$)/g, '')
// => "0"
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • This works fine..but it allows characters and spaces in between. Is there any way that we can eliminate space and characters in between. I somehow achieved by newValue.replace(/(^|,)0+/g, '$1').replace(/[^\d,]+/g, ''); – Jovial Andree May 27 '14 at 13:24
  • @JovialAndree, Do another replacement: `....replace(/\b0+(?!$)/g, '').replace(/[^\d,]/g, '')` – falsetru May 27 '14 at 13:31
  • Thanks @falsetru atlast i have done by this newValue.replace(/(^|,)0+/g, '$1').replace(/[^\d,]+/g, '').replace(/,,/g, ','); – Jovial Andree May 27 '14 at 13:38
  • @JovialAndree, You can replace the last part with this: `.replace(/,{2,}/g, ',.')` to handle the case where more than 2 consecutive commas. – falsetru May 27 '14 at 13:43