Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript replace string with 8 and 9 doesn't work...but other numbers do...?

Check out this script... run and see the oddity..

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, '')));
like image 347
Raphael Avatar asked Aug 17 '11 15:08

Raphael


People also ask

Why string replace is not working in JavaScript?

The "replace is not a function" error occurs when we call the replace() method on a value that is not of type string . To solve the error, convert the value to a string using the toString() method before calling the replace() method.

How do you replace multiple values in a string?

Show activity on this post. var str = "I have a cat, a dog, and a goat."; str = str. replace(/goat/i, "cat"); // now str = "I have a cat, a dog, and a cat." str = str. replace(/dog/i, "goat"); // now str = "I have a cat, a goat, and a cat." str = str.

How do you replace all occurrences of a character in a string in JavaScript?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag.

How replace all occurrences of a string in TypeScript?

To replace all occurrences of a string in TypeScript, use the replace() method, passing it a regular expression with the g (global search) flag. For example, str. replace(/old/g, 'new') returns a new string where all occurrences of old are replaced with new .


1 Answers

This is an Octal issue: try parseInt(val, 10). The leading zero makes it believe it's octal. parseInt takes a second optional parameter radix:

radix An integer that represents the radix of the above mentioned string. While this parameter is optional, always specify it to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified.

So:

parseInt('09') // 0
parseInt('09', 10); // 9
like image 157
Joe Avatar answered Nov 15 '22 00:11

Joe