用于将%放在数字后面的格式字符串

时间:2013-05-20 14:50:35

标签: javascript

试图找出如何将%附加到数字。数字长度各不相同,所以这是我不确定的。如何创建一个正则表达式,取任何数字,并附加%。

我在想这个,但你会怎样处理意外的长度?

"\\%d{DigitlegnthVariesHere}"

或者它是否像"\\%d"

那样简单

1 个答案:

答案 0 :(得分:9)

以下是如何在字符串中的每个(整个)编号后加%(编辑:请参阅下面的小数)

//                              In the "search for" regular expression:
//             +--------------- \d means "any digit"
//             | +------------- +  means "one or more of the previous thing"
//             | | +----------- The 'g' flag means "globally" in the string
//             | | |            --------------------------
//             | | |            In the replacement string:
//             | | |   +------- $& means "the text that matched"
//             | | |   | +----- % isn't special here, it's just a literal % sign
//             | | |   | |
//             V V V   V V
s = s.replace(/\d+/g, "$&%");

示例:

var s = "testing 123 testing 456";
s = s.replace(/\d+/g, "$&%");
console.log(s); // "testing 123% testing 456%"

在下面的评论中,你说:

  

问题如果输入像47.56这样的小数,它将输出45%56%

确实如此,因为\d仅适用于数字,因此它不会神奇地包含.

要处理小数,需要稍微复杂的表达式:

//                                    In the "search for" regular expression:
//             +--------------------- \d means "any digit"
//             | +------------------- +  means "one or more of the previous thing"
//             | |+------------------ (?:....) is a non-capturing group (more below)
//             | ||  +--------------- \. is a literal "."
//             | ||  | +------------- \d means "any digit" again
//             | ||  | |   +--------- ? means "zero or one of the previous thing,"
//             | ||  | |   |          which in this case is the non-capturing group
//             | ||  | |   |          containing (or not) the dot plus more digits
//             | ||  | |   | +------- The 'g' flag means "globally" in the string
//             | ||  | |   | |        --------------------------
//             | ||  | |   | |        In the replacement string:
//             | ||  | |   | |   +--- $& means "the text that matched"
//             | ||  | |   | |   | +- % isn't special here, it's just a literal % sign
//             | ||  | |   | |   | |
//             V VV  V V   V V   V V
s = s.replace(/\d+(?:\.\d+)?/g, "$&%");

基本上所说的是:匹配一系列数字可选后跟一个小数点和更多数字,并用匹配的字符和%替换它们。

示例:

var s = "testing 123.67 testing 456. And then...";
s = s.replace(/\d+(?:\.\d+)?/g, "$&%");
console.log(s); // "testing 123.67% testing 456%. And then..."

请注意,即使456后跟.,因为它后面没有更多数字,我们也没有在%之后添加.。 {1}}。


有一次,你的问题是“在数字之前而不是之后”。如果你真的想在数字的前面中找到它,只需在%之前移动$&

str = str.replace(/\d+/g, "%$&");