17

I have a scenario where I need to remove any leading zeros from a string like 02-03, 02&03, 02,03. I have this regex( s.replace(/^0+/, ''); ) to remove leading zeros but I need something which works for the above cases.

let strings = [`02-03`, `02&03`, `02`,`03`]
strings.forEach(s => {
  s = s.replace(/^0+/, '');
  console.log(s)
})

1

2 Answers 2

37

The simplest solution would probably be to use a word boundary (\b) like this:

s.replace(/\b0+/g, '')

This will remove any zeros that are not preceded by Latin letters, decimal digits, underscores. The global (g) flag is used to replace multiple matches (without that it would only replace the first match found).

$("button").click(function() {
  var s = $("input").val();
  
  s = s.replace(/\b0+/g, '');
  
  $("#out").text(s);
});
body { font-family: monospace; }
div { padding: .5em 0; }
#out { font-weight: bold; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><input value="02-03, 02&03, 02,03"><button>Go</button></div>
<div>Output: <span id="out"></span></div>

3
  • does not work for decimals. F.e. for "0.5" returns ".5" which is not desired
    – Glogo
    Feb 19, 2015 at 13:36
  • 4
    @Glogo well that wasn't part of the original requirements, but if that's necessary for your use case, you can use s.replace(/\b0+(0\.\d+)/g, '$1') to handle decimals, or s.replace(/\b(?:0*(0\.\d+)|0+)/g, '$1') to handle decimals or integers (note it requires a leading zero be present to recognize the decimal, e.g .005 will be treated as an integer).
    – p.s.w.g
    Feb 19, 2015 at 13:45
  • 1
    It stripes zeros also from the decimal part :( e.g. '0030.005' returns '30.5'
    – fllprbt
    Jul 22, 2020 at 11:28
2
s.replace(/\b0+[1-9]\d*/g, '')

should replace any zeros that are after a word boundary and before a non-zero digit. That is what I think you're looking for here.

1
  • Okay it compiles now, but it will only match numbers with at least 3 digits (so 02 won't be affected) and it will remove the entire number, not just the leading zeros.
    – p.s.w.g
    Jun 19, 2014 at 21:00

Not the answer you're looking for? Browse other questions tagged or ask your own question.