Javascript replace string with 8 and 9 does not work ... but do other numbers do ...?

Check out this script ... run and see weirdness.

http://jsfiddle.net/BjJTc/

From jsfiddle

var m = 'Jan07'; var mm = 'Jan'; alert(m.replace(mm, '')); alert(parseInt(m.replace(mm, ''))); var m = 'Jan08'; var mm = 'Jan'; alert(m.replace(mm, '')); alert(parseInt(m.replace(mm, ''))); var m = 'Jan09'; var mm = 'Jan'; alert(m.replace(mm, '')); alert(parseInt(m.replace(mm, ''))); var m = 'Jan10'; var mm = 'Jan'; alert(m.replace(mm, '')); alert(parseInt(m.replace(mm, ''))); 
+6
source share
4 answers

This is the Octal problem: try parseInt(val, 10) . Leading zero makes it be considered octal. parseInt takes the second optional radix parameter:

radix An integer that represents the base of the above string. Although this parameter is optional, always instruct it to eliminate the reader’s misunderstanding and ensure predictable behavior. Different implementations give different results when not specified.

So:

 parseInt('09') // 0 parseInt('09', 10); // 9 
+10
source

You have a problem with the base. Javascript interprets 07, 08, 09 as octal numbers. Decimal 7 and Octal 07 are evaluated with the same number, while 8 and 9 are not.

Include the base 10 radius as the second parameter for all your parseInt() calls:

 var m = 'Jan08'; var mm = 'Jan'; alert(m.replace(mm, '')); alert(parseInt(m.replace(mm, ''), 10)); // ------------------------------^^^^^^ 
+4
source

If you are trying to get the year from the string you have, you can try to parse it as a date and extract the number of years ...

 var m = 'Jan07'; var d = Date.parse('01' + m); // Parse the 1st of the month var y=Math.floor(d/(1000*60*60*24*365.24)) + 1970; // Convert to years since 1970, then add 1970 alert(y); 

Not for most elegant solutions, but you will get a year from your MMMyy format.

0
source

Or just lose the leading letters and any leading 0 -

 m='Jan08'; mm=/^\D+0?/,''); alert(m.replace(mm, '')); 
0
source

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


All Articles