Arun AK
Arun AK

Reputation: 4370

Why replace function is not working properly?

I have a number say 1,000 and i am going to convert comma into dot and i used the function

var x = "1,000";
x.replace(/,/g , ".");

So, the number became as 1.000. Now, i used the function below with the converted number

var x = x.replace(/./g , ",");

I should return 1,000 but it returns

,,,,,

I want to know the reason why it is returning like this.

Here is the Jsfiddle http://jsfiddle.net/d4N9s/2165/

Upvotes: 0

Views: 689

Answers (2)

Nagesh Sanika
Nagesh Sanika

Reputation: 1090

. means any character in Regular Expression you can use like this

var mystring = "1,000"
var mystring = mystring.replace(/,/g , ".");
alert(mystring);
var find=',';
var re = new RegExp(find, 'g');
var mystring = mystring.replace(re, ",");
alert(mystring);

Upvotes: 0

brso05
brso05

Reputation: 13222

. is a special character in regex you must escape it \. In regex . means any character so it is replacing all your characters with a ,.

Upvotes: 7

Related Questions