[javascript] Remove/ truncate leading zeros by javascript/jquery

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

This question is related to javascript jquery numbers zero

The answer is


Try this,

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

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

More here


Simply try to multiply by one as following:

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


If number is int use

"" + parseInt(str)

If the number is float use

"" + parseFloat(str)

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


const input = '0093';
const match = input.match(/^(0+)(\d+)$/);
const result = match && match[2] || input;

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


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)


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


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"

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>

parseInt(value) or parseFloat(value)

This will work nicely.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to numbers

how to display a javascript var in html body How to label scatterplot points by name? Allow 2 decimal places in <input type="number"> Why does the html input with type "number" allow the letter 'e' to be entered in the field? Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array Input type "number" won't resize C++ - how to find the length of an integer How to Generate a random number of fixed length using JavaScript? How do you check in python whether a string contains only numbers? Turn a single number into single digits Python

Examples related to zero

JAVA How to remove trailing zeros from a double Check if bash variable equals 0 How to create a numeric vector of zero length in R How to remove rows with any zero value Remove/ truncate leading zeros by javascript/jquery PHP prepend leading zero before single digit number, on-the-fly Fastest way to zero out a 2d array in C? Nullable types: better way to check for null or zero in c#