Regular Expression for formatting numbers in JavaScript(用于在 JavaScript 中格式化数字的正则表达式)
问题描述
我需要使用 JavaScript 在网页上显示格式化的数字.我想格式化它,以便在正确的位置有逗号.我将如何使用正则表达式来做到这一点?我已经做到了这样的事情:
I need to display a formatted number on a web page using JavaScript. I want to format it so that there are commas in the right places. How would I do this with a regular expression? I've gotten as far as something like this:
myString = myString.replace(/^(d{3})*$/g, "${1},");
...然后意识到这将比我想象的更复杂(并且上面的正则表达式 甚至没有接近我需要的).我已经进行了一些搜索,但我很难找到适合这个的东西.
...and then realized this would be more complex than I think (and the regex above is not even close to what I need). I've done some searching and I'm having a hard time finding something that works for this.
基本上,我想要这些结果:
Basically, I want these results:
- 45 变成 45
- 3856 变为 3,856
- 398868483992 变为 398,868,483,992
...你明白了.
推荐答案
这可以在单个正则表达式中完成,无需迭代.如果您的浏览器支持 ECMAScript 2018,您可以简单地使用环视并在正确的位置插入逗号:
This can be done in a single regex, no iteration required. If your browser supports ECMAScript 2018, you could simply use lookaround and just insert commas at the right places:
搜索 (?<=d)(?=(ddd)+(?!d))
并全部替换为 ,
Search for (?<=d)(?=(ddd)+(?!d))
and replace all with ,
在旧版本中,JavaScript 不支持后视,因此这不起作用.幸运的是,我们只需要稍作改动:
In older versions, JavaScript doesn't support lookbehind, so that doesn't work. Fortunately, we only need to change a little bit:
搜索 (d)(?=(ddd)+(?!d))
并全部替换为 1,
Search for (d)(?=(ddd)+(?!d))
and replace all with 1,
所以,在 JavaScript 中,它看起来像:
So, in JavaScript, that would look like:
result = subject.replace(/(d)(?=(ddd)+(?!d))/g, "$1,");
说明:断言从字符串中的当前位置开始,可以匹配三的倍数的数字,并且在当前位置的左边有一个数字.
Explanation: Assert that from the current position in the string onwards, it is possible to match digits in multiples of three, and that there is a digit left of the current position.
这也适用于小数 (123456.78),只要点右侧"没有太多数字(否则你会得到 123,456.789,012).
This will also work with decimals (123456.78) as long as there aren't too many digits "to the right of the dot" (otherwise you get 123,456.789,012).
也可以在 Number 原型中定义,如下:
You can also define it in a Number prototype, as follows:
Number.prototype.format = function(){
return this.toString().replace(/(d)(?=(d{3})+(?!d))/g, "$1,");
};
然后像这样使用它:
var num = 1234;
alert(num.format());
学分:Jeffrey Friedl,掌握正则表达式,第 3 期.版, p.66-67
Credit: Jeffrey Friedl, Mastering Regular Expressions, 3rd. edition, p. 66-67
这篇关于用于在 JavaScript 中格式化数字的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:用于在 JavaScript 中格式化数字的正则表达式
基础教程推荐
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 动态更新多个选择框 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01