Javascript Regex: replacing last semicolon
I have the following code:
var x = "100.007" x = String(parseFloat(x).toFixed(2)); return x => 100.01 This works great as I want it to work. I just want a tiny addition, 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 "," where I want to catch the last. Any help would be appreciated.
You can do this with a regex:
x = x.replace(/,([^,]*)$/, ".$1"); This regular expression matches a comma, followed by any amount of text that does not contain a comma. A replacement string is just a period followed by everything after the last comma. Other commas preceding this in the line will not be affected.
Now, if you are really converting numbers formatted in the "European style" (due to the lack of a better term), you will also have to worry about the ".". characters in places where the number "style in the style of the USA" will have a comma. I think you probably just want to get rid of them:
x = x.replace(/\./g, ''); When you use the ".replace ()" function in a string, you must understand that it returns the modified string. However, it does not change the original string, so a statement like:
x.replace(/something/, "something else"); does not affect the value of "x".
You can do this using lastIndexOf () to find the last occurrence , and replace it.
An alternative is to use a regular expression with a line break marker:
myOldString.replace(/,([^,]*)$/, ".$1");