Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript to trim started 0 in a string

Tags:

javascript

I hava a time string,the format is HHMM, I need to get the decimal of it, how can I do ?

e.g.

'1221'=1221

'0101'=101

'0011'=11

'0001'=1

If the string begins with "0x", the radix is 16 (hexadecimal)

If the string begins with "0", the radix is 8 (octal).

But I want to treat it as decimal no matter whether started with 0 or 00 or 000.


additional:

thanks all.

I had know what you said, what make I confused as following :

var temp1=0300; var temp2='0300';

parseInt(temp1,10)=192; parseInt(temp1,10)=300;

so I I doubt parseInt() and have this question .

like image 634
Cong De Peng Avatar asked Dec 17 '22 05:12

Cong De Peng


2 Answers

Use parseInt() and specify the radix yourself.

parseInt("10")     // 10
parseInt("10", 10) // 10
parseInt("010")    //  8
parseInt("10", 8)  //  8
parseInt("0x10")   // 16
parseInt("10", 16) // 16

Note: You should always supply the optional radix parameter, since parseInt will try to figure it out by itself, if it's not provided. This can lead to some very weird behavior.


Update:

This is a bit of a hack. But try using a String object:

var s = "0300";

parseInt(s, 10); // 300

The down-side of this hack is that you need to specify a string-variable. None of the following examples will work:

parseInt(0300 + "", 10);              // 192    
parseInt(0300.toString(), 10);        // 192    
parseInt(Number(0300).toString(), 10) // 192
like image 63
cllpse Avatar answered Dec 28 '22 09:12

cllpse


If you want to keep it as a string, you can use regex:

num = num.replace(/^0*/, "");

If you want to turn it unto a number roosteronacid has the right code.

like image 41
Glenn Avatar answered Dec 28 '22 07:12

Glenn