如何使用JavaScript正規表示式顯示數值千分位

6 月 14, 2019 | | 0 條留言

JavaScript如何使用正規表示式顯示數值千分位

n = 1279834847944074100465236.33;
re = /(d{1,3})(?=(d{3})+(?:$|D))/g ;
n1 = n.replace(re,$1,);

Demo

See the Pen How does JavaScript display a numeric thousand position using a regular expression? by Leon Cheng (@jq153387) on CodePen. 專案中如果有使用到正則表示,在Safari瀏覽器會在某個正則規則下,無法解析出來,就會出現 SyntaxError: Invalid regular expression: invalid group specifier name 的錯誤,然後整個網頁就會空白。

直接把正則包在/..../裡面是會出錯的,必須要用new RegExp("......", 'g')包起來才可以,並且有使用到\d的都要用兩個斜線取代\\d

以下可改寫使用方法new RegExp()解決Safari瀏覽器相容性問題。

const priceFormat = (val) => {
  const re = new RegExp((\\d{1,3})(?=(\\d{3})+(?:$|\\D)), g);
  return val?.toString().replace(re, $1,);
};

參考資料: React stepping pit: Invalid regular expression: invalid group specifier name