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.
var s = "01";
s = s.replace(/^0+/, '');
alert(s);
Use the inbuilt replaceAll() method of the String class which accepts two parameters, a Regular Expression, and a Replacement String. To remove the leading zeros, pass a Regex as the first parameter and empty string as the second parameter. This method replaces the matched value with the given string.
To remove the leading zeros from a number, call the parseInt() function, passing it the number and 10 as parameters, e.g. parseInt(num, 10) . The parseInt function parses a string argument and returns a number with the leading zeros removed.
Use parseInt() to remove leading zeros from a number in JavaScript.
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With