user400749
user400749

Reputation: 195

JavaScript check for the first zero in 2 digits

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 become:

1
2
3

whereas:

11
12
13

will not change.

How to do that?

Upvotes: 0

Views: 4543

Answers (6)

jonycheung
jonycheung

Reputation: 850

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))

Upvotes: 0

Erik
Erik

Reputation: 4105

You could do something like this:

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

Upvotes: 5

kookaburra
kookaburra

Reputation: 21

Very simple

var str = "07";  
str = Number(str);  
alert(str); // will return 7

Upvotes: 2

m0sa
m0sa

Reputation: 10940

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());​

Upvotes: 0

124697
124697

Reputation: 21893

use .replace()

for example...

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

then parseInt back back to int

int int1 = string1.parseInt();

Upvotes: 0

Ta01
Ta01

Reputation: 31630

if str.substring(0) = "0" && str.length == 2
   str = str.substring(1);

Upvotes: 0

Related Questions