Remove leading zeros of a string in Javascript
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.
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>