Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove leading zeros of a string in Javascript [duplicate]

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);
like image 942
Lucky Avatar asked Jun 19 '14 20:06

Lucky


People also ask

How do you remove leading zeros from a string?

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.

How do you remove leading zeros from a string in typescript?

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.

Does parseInt remove leading zeros?

Use parseInt() to remove leading zeros from a number in JavaScript.


2 Answers

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>
like image 139
p.s.w.g Avatar answered Oct 01 '22 08:10

p.s.w.g


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.

like image 34
La-comadreja Avatar answered Oct 01 '22 07:10

La-comadreja