How to replace some special characters with a number?

I have a number, say 2500.00, and I want to convert the number to 2.500.00. Thus, we can replace the special character, replacing it with

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

and for "Dot" we can do it too. But in this case, this will not work, because when we use the substitution function for the comma, as indicated above, the number will become 2.500.00, and if we apply now, it will become 2500.00.

So, is there a way to convert 2,500.00 to 2,500,00?

+4
source share
5 answers

You can use:

 var x = '2,123,500.00'; var arr = x.split('.'); var y = arr[0].replace(/,/g, '.') + ',' + arr[1]; //=> 2.123.500,00 
+2
source

String.prototype.replace can execute the function:

 '2,123,500.00'.replace(/[,.]/g, function(c){ return c===',' ? '.' : ','; }); 
+3
source

You are lucky .replace() to accept the function as the second argument. This function has a matched string as an argument, and the return value will be replace_by value of .replace() .

In short, you can simply check what matches the string and return the correct value:

 var str = "2,500.00"; var changed_str = str.replace(/,|\./g, function(old){ if (old === '.') return ','; else if (old === ',') return '.'; }); document.write(changed_str) 
+1
source

Why not use the built-in methods to format your numbers correctly?

Number.toLocaleString() will work Number.toLocaleString() fine.

If you really have a number, as you said, you can easily achieve this using the correct language. If you have a string representation of your number, you will have to parse it first.

0
source

This (now) works for any number of commas or points, even if end or leading points or commas.

HTML:

 <div id="result"></div> 

JS:

 var x = '.,2.123,50.0.00.'; var between_dots = x.split('.'); for (var i = 0; i < between_dots.length; i++) { between_dots[i] = between_dots[i].replace(/,/g, '.'); } var y = between_dots.join(','); document.getElementById('result').innerHTML = y; 

Here is jsfiddle

-one
source

All Articles