100.01 ...">

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.

+5
source share
5 answers

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".

+15
source

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"); 
+2
source

You can use lastIndexOf to find the last occurrence lastIndexOf You can then use slice to place the part before and after , along with . between them.

+1
source

You can use regex. You want to replace the last ",", so the main idea is to replace the "," for which there is no "," after.

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

Will return what you want :-).

+1
source

You do not need to worry about whether this is the last β€œ.” Because there is only one. JavaScript does not store numbers inside with commas or dot separators.

0
source

Source: https://habr.com/ru/post/887275/


All Articles