問題描述
我需要使用 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 中格式化數字的正則表達式的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!