Reputation: 195
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
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
Reputation: 21
Very simple
var str = "07";
str = Number(str);
alert(str); // will return 7
Upvotes: 2
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
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
Reputation: 31630
if str.substring(0) = "0" && str.length == 2
str = str.substring(1);
Upvotes: 0