111

Suggest solution for removing or truncating leading zeros from number(any string) by javascript,jquery.

Somnath Muluk
  • 55,015
  • 38
  • 216
  • 226

17 Answers17

258

You can use a regular expression that matches zeroes at the beginning of the string:

s = s.replace(/^0+/, '');
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • @Guffa:I am using it in jquery code..may be because of that it might not working. – Somnath Muluk Nov 26 '11 at 05:44
  • 3
    @Somnath, jQuery IS javascript. If something works in javascript it will continue to work if you happen to be using jQuery as well. – Abe Miessler Nov 26 '11 at 05:55
  • 5
    Why the downvote? If you don't explain what you think is wrong, it can't improve the answer. – Guffa Mar 01 '12 at 10:28
  • 5
    s = s.replace(/^0+/, '') will convert "00" to in "" (empty string instead of string with one zero in), which in most cases is undesirable, better encapsulate it in a function and add the line: if (s == "") s = "0"; – Oliver Konig Mar 02 '15 at 06:12
  • 1
    This regex has an issue if you have all zeros, `"0000"`. The issue can be fixed with positive lookahead: `.replace(/^0+/, '')` – Peter Thoeny Feb 11 '21 at 05:06
  • What is about if we have 0.45 and I want to keep at least one 0? – yasserpulido Jan 10 '23 at 23:36
46

I would use the Number() function:

var str = "00001";
str = Number(str).toString();
>> "1"

Or I would multiply my string by 1

var str = "00000000002346301625363";
str = (str * 1).toString();
>> "2346301625363"
Jade Hamel
  • 1,360
  • 1
  • 15
  • 30
  • 3
    it will not work with value bigger than 2^53. Number("009007199254740993").toString() will be "9007199254740992" – madreason Apr 20 '17 at 11:54
  • 1
    Well I'll be more impressed to face a situation where having to remove leading zeros in a "String" that is bigger than "009007199254740993" than seeing the solution... Personally I would rather put a validation on the input to tell the dude who typed it he is probably drunk and should not send – Jade Hamel Aug 16 '21 at 23:18
17

Maybe a little late, but I want to add my 2 cents.

if your string ALWAYS represents a number, with possible leading zeros, you can simply cast the string to a number by using the '+' operator.

e.g.

x= "00005";
alert(typeof x); //"string"
alert(x);// "00005"

x = +x ; //or x= +"00005"; //do NOT confuse with x+=x, which will only concatenate the value
alert(typeof x); //number , voila!
alert(x); // 5 (as number)

if your string doesn't represent a number and you only need to remove the 0's use the other solutions, but if you only need them as number, this is the shortest way.

and FYI you can do the opposite, force numbers to act as strings if you concatenate an empty string to them, like:

x = 5;
alert(typeof x); //number
x = x+"";
alert(typeof x); //string

hope it helps somebody

DiegoDD
  • 1,625
  • 4
  • 21
  • 32
  • it will not work with value bigger than 2^53. (+"009007199254740993").toString() will be "9007199254740992" – madreason Apr 20 '17 at 11:53
  • This is a very clean solution when working with small numbers. Thanks for this tip, person from 2013! =D – Partack May 07 '21 at 14:11
14

Since you said "any string", I'm assuming this is a string you want to handle, too.

"00012  34 0000432    0035"

So, regex is the way to go:

var trimmed = s.replace(/\b0+/g, "");

And this will prevent loss of a "000000" value.

var trimmed = s.replace(/\b(0(?!\b))+/g, "")

You can see a working example here

Somnath Muluk
  • 55,015
  • 38
  • 216
  • 226
John Fisher
  • 22,355
  • 2
  • 39
  • 64
6
parseInt(value) or parseFloat(value)

This will work nicely.

Krupall
  • 379
  • 3
  • 7
3

Simply try to multiply by one as following:

"00123" * 1;              // Get as number
"00123" * 1 + "";       // Get as string

Siyavash Hamdi
  • 2,764
  • 2
  • 21
  • 32
3

1. The most explicit is to use parseInt():

parseInt(number, 10)

2. Another way is to use the + unary operator:

+number

3. You can also go the regular expression route, like this:

number.replace(/^0+/, '')
Surya R Praveen
  • 3,393
  • 1
  • 24
  • 25
3

I got this solution for truncating leading zeros(number or any string) in javascript:

<script language="JavaScript" type="text/javascript">
<!--
function trimNumber(s) {
  while (s.substr(0,1) == '0' && s.length>1) { s = s.substr(1,9999); }
  return s;
}

var s1 = '00123';
var s2 = '000assa';
var s3 = 'assa34300';
var s4 = 'ssa';
var s5 = '121212000';

alert(s1 + '=' + trimNumber(s1));
alert(s2 + '=' + trimNumber(s2));
alert(s3 + '=' + trimNumber(s3));
alert(s4 + '=' + trimNumber(s4));
alert(s5 + '=' + trimNumber(s5));
// end hiding contents -->
</script>
Somnath Muluk
  • 55,015
  • 38
  • 216
  • 226
  • 6
    That's not very good code. The check for the string length is totally superflous, it will never be evaluated to `false`. The use of `9999` as the second parameter to `substr` is not needed. Just use `while (s.substr(0,1) == '0') s = s.substr(1);`. Besides, that code snippet looks really old, the `language` attribute of the `script` tag has been deprecated for a long time, and using comments inside `script` tags is only needed for browsers that doesn't understand the `script` tag at all, e.g. Internet Explorer 1.0. – Guffa Mar 01 '12 at 10:38
2

Try this,

   function ltrim(str, chars) {
        chars = chars || "\\s";
        return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
    }

    var str =ltrim("01545878","0");

More here

Gowri
  • 16,587
  • 26
  • 100
  • 160
1

You should use the "radix" parameter of the "parseInt" function : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FparseInt

parseInt('015', 10) => 15

if you don't use it, some javascript engine might use it as an octal parseInt('015') => 0

antoine
  • 618
  • 7
  • 16
1

If number is int use

"" + parseInt(str)

If the number is float use

"" + parseFloat(str)
Robert
  • 10,403
  • 14
  • 67
  • 117
loakesh bachhu
  • 323
  • 3
  • 4
1

const number = '0000007457841'; console.log(+number) //7457841;

OR number.replace(/^0+/, '')

Vivek Kapoor
  • 431
  • 6
  • 7
1

Regex solution from Guffa, but leaving at least one character

"123".replace(/^0*(.+)/, '$1'); // 123
"012".replace(/^0*(.+)/, '$1'); // 12
"000".replace(/^0*(.+)/, '$1'); // 0
Joost
  • 3,169
  • 2
  • 22
  • 40
1

Use "Math.abs"

eg: Math.abs(003) = 3;

console.log(Math.abs(003))
1

I wanted to remove all leading zeros for every sequence of digits in a string and to return 0 if the digit value equals to zero.

And I ended up doing so:

str = str.replace(/(0{1,}\d+)/, "removeLeadingZeros('$1')")

function removeLeadingZeros(string) {
    if (string.length == 1) return string
    if (string == 0) return 0
    string = string.replace(/^0{1,}/, '');
    return string
}
0

One another way without regex:

function trimLeadingZerosSubstr(str) {
    var xLastChr = str.length - 1, xChrIdx = 0;
    while (str[xChrIdx] === "0" && xChrIdx < xLastChr) {
        xChrIdx++;
    }
    return xChrIdx > 0 ? str.substr(xChrIdx) : str;
}

With short string it will be more faster than regex (jsperf)

madreason
  • 437
  • 4
  • 17
0
const input = '0093';
const match = input.match(/^(0+)(\d+)$/);
const result = match && match[2] || input;
Boney
  • 2,072
  • 3
  • 18
  • 23