Javascript正则表达式:替换逗号的最后一个点 [英] Javascript Regex: replacing the last dot for a comma

查看:152
本文介绍了Javascript正则表达式:替换逗号的最后一个点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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.

推荐答案

你可以使用正则表达式:

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的值没有影响。

这篇关于Javascript正则表达式:替换逗号的最后一个点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆