Jahe JS
Jahe JS

Reputation: 91

Javascript replace dots with regular expression, but not works

I'm sorry, but I can't find working dot replacement on stackoverflow. Peoples ask about replacing

var str = '. 950.000.000, -';
str = str.replace(/\./gi, '');
alert(parseInt(str)); // yes, it works & will output correctly

But, it wouldn't works, when my 'str' var is : Rp. 950.000,- . It is currency format in my area, and i want to do math with it. I do this, and not work:

var str = 'Rp. 950.000, -';
str = str.replace(/\./gi, '');// i dont know, but the str values now is nothing
alert(parseInt(str)); // sure, it outputs nothing

I just want to replace all dots (so it will not bothers math operation, because dot is a decimal on number).

Upvotes: 0

Views: 1053

Answers (2)

Kevin Bowersox
Kevin Bowersox

Reputation: 94469

Why not replace everything that is not a number with \D?

var str = 'Rp. 950.000, -';
str = str.replace(/\D/gi, '');// i dont know, but the str values now is nothing
alert(parseInt(str, 10));

Working Example http://jsfiddle.net/e8dMD/1/

Upvotes: 2

Andrew Clark
Andrew Clark

Reputation: 208475

After removing all the dots in the string 'Rp. 950.000, -' you will be left with 'Rp 950000, -'. If you try to use this string for parseInt() it will fail because of the letters at the beginning and the other characters at the end. If you want to remove all non-digit characters from you string you can use the following:

str = str.replace(/\D/g, '');

After this parseInt() should work fine and give you 950000.

Upvotes: 0

Related Questions