且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Javascript正则表达式:替换逗号的最后一个点

更新时间:2023-02-17 23:40:47

你可以使用正则表达式:

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, '');

当你对字符串使用.replace()函数时,你应该明白它返回修改后的字符串。但是,它不会修改原始字符串,因此声明如下:

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");

对x的值没有影响。