問題描述
我需要使用 JavaScript 在網(wǎng)頁上顯示格式化的數(shù)字.我想格式化它,以便在正確的位置有逗號.我將如何使用正則表達(dá)式來做到這一點?我已經(jīng)做到了這樣的事情:
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},");
...然后意識到這將比我想象的更復(fù)雜(并且上面的正則表達(dá)式 甚至沒有接近我需要的).我已經(jīng)進(jìn)行了一些搜索,但我很難找到適合這個的東西.
...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.
基本上,我想要這些結(jié)果:
Basically, I want these results:
- 45 變成 45
- 3856 變?yōu)?3,856
- 398868483992 變?yōu)?398,868,483,992
...你明白了.
推薦答案
這可以在單個正則表達(dá)式中完成,無需迭代.如果您的瀏覽器支持 ECMAScript 2018,您可以簡單地使用環(huán)視并在正確的位置插入逗號:
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,");
說明:斷言從字符串中的當(dāng)前位置開始,可以匹配三的倍數(shù)的數(shù)字,并且在當(dāng)前位置的左邊有一個數(shù)字.
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.
這也適用于小數(shù) (123456.78),只要點右側(cè)"沒有太多數(shù)字(否則你會得到 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());
學(xué)分:Jeffrey Friedl,掌握正則表達(dá)式,第 3 期.版, p.66-67
Credit: Jeffrey Friedl, Mastering Regular Expressions, 3rd. edition, p. 66-67
這篇關(guān)于用于在 JavaScript 中格式化數(shù)字的正則表達(dá)式的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!