Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Regex: replacing the last dot for a comma

I have the following code:

var x = "100.007"
x = String(parseFloat(x).toFixed(2));
return x
=> 100.01

This works awesomely just how I want it to work. I just want a tiny addition, which is something like:

var x = "100,007"
x.replace(",", ".")
x.replace
x = String(parseFloat(x).toFixed(2));
x.replace(".", ",")
return x
=> 100,01

However, this code will replace the first occurrence of the ",", where I want to catch the last one. Any help would be appreciated.

like image 738
Shyam Avatar asked Jan 30 '11 15:01

Shyam


People also ask

How to replace all dot with comma in JavaScript?

An alternative to using the replaceAll method is to use the replace method with the g (global) flag. Use the replace() method to replace all commas with dots, e.g. const replaced = str1. replace(/,/g, '. '); .

What is $1 in regex replace?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.

What is regex in replace?

The Regex. Replace(String, String, MatchEvaluator, RegexOptions) method is useful for replacing a regular expression match if any of the following conditions is true: If the replacement string cannot readily be specified by a regular expression replacement pattern.


1 Answers

You can do it with a regular expression:

x = x.replace(/,([^,]*)$/, ".$1");

That regular expression matches a comma followed by any amount of text not including a comma. The replacement string is just a period followed by whatever it was that came after the original last comma. Other commas preceding it in the string won't be affected.

Now, if you're really converting numbers formatted in "European style" (for lack of a better term), you're also going to need to worry about the "." characters in places where a "U.S. style" number would have commas. I think you would probably just want to get rid of them:

x = x.replace(/\./g, '');

When you use the ".replace()" function on a string, you should understand that it returns the modified string. It does not modify the original string, however, so a statement like:

x.replace(/something/, "something else");

has no effect on the value of "x".

like image 191
Pointy Avatar answered Sep 21 '22 12:09

Pointy