使用正则表达式在jQuery中将字符前置为字符串

时间:2013-10-01 18:14:06

标签: javascript jquery regex

我正在尝试使用正则表达式在某些字符串的开头添加一个字符,但我对它很新,似乎无法找到我正在寻找的答案。我有Below 1499Above 1900等字符串,我想在数字字符串的开头添加$。这是我必须找到的代码(顺便说一句,这些都是div中的文本字符,带有一个refinement_price_text类):

$('.refinement_price_text').each(function(){
    console.log($(this).text().match(/\d{1,5}/g));
});

它将它们很好地记录到控制台。它们被记录为具有一个项目的数组。我现在不知道如何为他们添加一个美元符号。我试过prepend(),但这不起作用。我试图将match()设置为变量,但这不起作用。我想最初使用replace(),但我需要保持当前的值,只需将美元符号字符添加到开头,我不知道$(this)等价于正则表达式是为了保持相同的价值观。

让我知道这是否有意义。我确定必须有一个能够轻松完成此功能的功能吗?谢谢你的帮助!

2 个答案:

答案 0 :(得分:2)

我相信这可以处理所有可能性:

"111 Above 1499 and below 14930 and $100".replace(/([^$]|^)(\b\d+)/g, "$1$$$2")
> "$111 Above $1499 and below $14930 and $100"

替换Jquery中的文本:

$(this).text(function(i, t) { return t.replace(...above stuff...) })

http://jsfiddle.net/k7XJw/1/

忽略数字是括号,

str = "111 Above 1499 and below 14930(55) and $100 and (1234) and (here 123) and (123 there)"
str.replace(/([^$(]|^)(\b\d+\b)(?!\))/g, "$1$$$2")
> "$111 Above $1499 and below $14930(55) and $100 and (1234) and (here 123) and (123 there)"

答案 1 :(得分:0)

对于简单的字符串,例如您发布的前瞻性正则表达式和替换将起作用。 基本上告诉正则表达式找到字符串中的第一个数字(但不要消耗它)然后添加一个美元符号。对于同一个字符串中的多个数字,您必须调整正则表达式。

var s = "before 1900"
s=s.replace(/(?=[0-9])/,"$");
console.log(s);

修改以支持多次出现。它查找以空格开头的任何数字,然后将美元符号添加到该数字。

Plunker example

var s = "before 1900 and 2130 and (1900)"
s=s.replace(/\s(?=\d)/g," $");
console.log(s);