簡體   English   中英

JavaScript正則表達式-格式為帶尾隨零和字符串的十進制

[英]JavaScript regex - Format decimal with trailing zero and string

我有不同的價格格式,需要顯示如下:

1.09-----> 1.09
1.00----> 1
1.00 lb --->1lb
1.09 lb---->1.09lb

我需要構建JavaScript正則表達式以指定格式顯示以上價格的幫助。

使用parseFloatNumber.toString解析並格式化數字部分。 添加特殊情況以處理LB:

function formatPrice(price) {
    return parseFloat(price) + (price.match(/ .+$/) ? price.match(/ (.+)$/)[1] : "");
}

console.log(formatPrice("1.00"));    // 1
console.log(formatPrice("1.09"));    // 1.09
console.log(formatPrice("1.09000")); // 1.09
console.log(formatPrice("1.00 lb")); // 1lb
console.log(formatPrice("1.09 lb")); // 1.09lb
console.log(formatPrice("1.09 kg")); // 1.09kg

您可以嘗試以下正則表達式,

> "1.09 lb".replace(/\.00|\s+/g, "");
'1.09lb'
> "1.00 lb".replace(/\.00|\s+/g, "");
'1lb'
> "1.00".replace(/\.00|\s+/g, "");
'1'
> "1.09".replace(/\.00|\s+/g, "");
'1.09'

要刪除兩個以上的零,

> "1.000".replace(/\.00+|\s+/g, "");
'1'

你可以試試

\.0+\s*(\D*)$|[ ]+

補發: $1

這是在線演示

樣例代碼:

var re = /\.0+\s*(\D*)$|[ ]+/g;
var str = '1.09\n1.00\n1.00 lb\n1.09 lb';
var subst = '$1';

var result = str.replace(re, subst);

輸出:

1.09
1
1lb
1.09lb

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM