Javascript to crop started 0 in line

I hava temporary string, HHMM format, I need to get a decimal number, how can I do this?

eg.

'1221' = 1221

'0101' = 101

'0011' = 11

'0001' = 1

If the line starts with "0x", the radius is 16 (hexadecimal)

If the line starts with "0", the radius is 8 (octal).

But I want to treat it as a decimal regardless of whether it starts with 0 or 00 or 000.


additional:

thank you all.

I knew what you said, which makes me confuse the following:

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

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

so I doubt parseInt () and ask this question.

+3
source share
5

parseInt() .

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

. radix, parseInt , . .



Update:

. String:

var s = "0300";

parseInt(s, 10); // 300

, . :

parseInt(0300 + "", 10);              // 192    
parseInt(0300.toString(), 10);        // 192    
parseInt(Number(0300).toString(), 10) // 192
+6

radix parseInt():

var x = '0123';
x = parseInt(x, 10); // x == 123
+2

, regex:

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

, roosteronacid .

+2
Number("0300") = Number(0300) = 300
0

:

function parse_int(num) {
    var radix = 10;
    if (num.charAt(0) === '0') {
        switch (num.charAt(1)) {
        case 'x':
            radix = 16;
            break;
        case '0':
            radix = 10;
            break;
        default:
            radix = 8;
            break;
    }
    return parseInt(num, radix);
}
var num8 = '0300';
var num16 = '0x300';
var num10 = '300';
parse_int(num8);  // 192
parse_int(num16); // 768
parse_int(num10); // 300
0

Source: https://habr.com/ru/post/1718779/


All Articles