正则表达式在JavaScript中格式化数字 [英] Regular Expression for formatting numbers in JavaScript

查看:169
本文介绍了正则表达式在JavaScript中格式化数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用JavaScript在网页上显示一个格式化的数字。我想格式化,以便在正确的地方有逗号。我如何用正则表达式来做到这一点?我已经得到了这样的事情:

  myString = myString.replace(/ ^(\d {3} )* $ / g,$ {1},); 

...然后意识到这会比我想象的更复杂(上面的正则表达式是<甚至不需要关闭来满足我的需要)。我已经做了一些搜索,我很难找到适合这个的东西。



基本上,我想要这些结果:


  • 45变成45
    3856变成3,856
  • 398868483992变成398,868,483,992



...你明白了。这可以在一个正则表达式中完成,不需要迭代。如果您不使用JavaScript,则可以简单地使用lookaround,并在正确的位置插入逗号。



搜索(?<= \ d)(?=(\d\d\d)+(?!\d))并全部替换为

搜索(\ d)(?=(\ d \ d \\ \\ d)+(?!\d))并全部替换为 \ 1,



所以,在JavaScript中,它看起来像:

  result = subject.replace(/(\d )(?=(\ d \d\d)+(?!\d))/ g,$ 1,); 

说明:从字符串中的当前位置断言,可以将数字以倍数三位数字,还有一位数字留在当前位置。

这也可以用小数(123456.78),只要没有太多的数字到点的右边(否则你得到123,456,789,012)。

你也可以在一个数字原型中定义它,如下所示:



$ $ p $ Number.prototype.format = function(){
return this.toString()。replace(/(\ d)(?= (\d {3})+(?!\d))/ g,$ 1);
};

然后像这样使用它:

  var num = 1234; 
alert(num.format());

信用:Jeffrey Friedl,掌握正则表达式,3rd。版本,p。 66-67

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 becomes 45
  • 3856 becomes 3,856
  • 398868483992 becomes 398,868,483,992

...you get the idea.

解决方案

This can be done in a single regex, no iteration required. If you weren't using JavaScript, you could simply use lookaround and just insert commas at the right places:

Search for (?<=\d)(?=(\d\d\d)+(?!\d)) and replace all with ,

But JavaScript doesn't support lookbehind, so that doesn't work. Fortunately, we only need to change a little bit:

Search for (\d)(?=(\d\d\d)+(?!\d)) and replace all with \1,

So, in JavaScript, that would look like:

result = subject.replace(/(\d)(?=(\d\d\d)+(?!\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.

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

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

And then using it like this:

var num = 1234;
alert(num.format());

Credit: Jeffrey Friedl, Mastering Regular Expressions, 3rd. edition, p. 66-67

这篇关于正则表达式在JavaScript中格式化数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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