admin管理员组

文章数量:1390949

I have a text field with 2 digits in it as user input. I want to take out the first digit if its 0.

Example

01
02
03

will bee:

1
2
3

whereas:

11
12
13

will not change.

How to do that?

I have a text field with 2 digits in it as user input. I want to take out the first digit if its 0.

Example

01
02
03

will bee:

1
2
3

whereas:

11
12
13

will not change.

How to do that?

Share Improve this question edited Jan 8, 2023 at 9:37 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Dec 12, 2010 at 18:16 user400749user400749 1951 gold badge4 silver badges12 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 5

You could do something like this:

var a="07";
alert(a-0);

Very simple

var str = "07";  
str = Number(str);  
alert(str); // will return 7
if str.substring(0) = "0" && str.length == 2
   str = str.substring(1);

use .replace()

for example...

    if(string1.substring(0) =="0"){
    string1.substring(0).replace("0","");
      }

then parseInt back back to int

int int1 = string1.parseInt();

If you realy have 2 digits:

var str = "09";
str = str[0] === '0' ? str[1] : str;

Or you can take a more general approach

String.prototype.trimLeadingZeros = function () {
  var x = this || '', i;
  for(i = 0;i < x.length; i++) {
    if(x[i] !== '0') {
      return x.substring(i);
    }
  }
};

​window.alert("000000102305"​.trimLeadingZeros());​

This is because Javascript is interpreting the values as string. You can use 2 ways to convert. Assuming you save the digit into a variable called myNumber: var myNumber = "01";

1st way is to type the assignment

myNumber = Number(myNumber);

2nd way is to use the parseInt function

myNumber = parseInt(myNumber);

If later, you want the variable in String again

myNumber = String(myNumber);

Or better yet, you can do everything on one line.

var myNumber = String(Number(myNumber))

and

var myNumber = String(parseInt(myNumber))

本文标签: JavaScript check for the first zero in 2 digitsStack Overflow