JS - 使用正则表达式获取字符串替换的原始值

时间:2013-12-28 21:24:50

标签: javascript regex

我们有一个字符串:

var dynamicString = "This isn't so dynamic, but it will be in real life.";

某些输入中的用户类型:

var userInput = "REAL";

我希望在此输入上进行匹配,并使用span来包装它以突出显示它:

var result = " ... but it will be in <span class='highlight'>real</span> life.";

所以我使用一些RegExp魔术来做到这一点:

// Escapes user input,
var searchString = userInput.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");

// Now we make a regex that matches *all* instances 
// and (most important point) is case-insensitive.
var searchRegex = new RegExp(searchString , 'ig');

// Now we highlight the matches on the dynamic string:
dynamicString = dynamicString.replace(reg, '<span class="highlight">' + userInput + '</span>');

这一切都很棒,除非是结果:

console.log(dynamicString);
// -> " ... but it will be in <span class='highlight'>REAL</span> life.";

我用用户的输入替换了内容,这意味着现在文本会使用户的内容不敏感。

如何用上面显示的范围包装所有匹配,同时保持匹配的原始值?

想通了,理想的结果是:

// user inputs 'REAL',

// We get:
console.log(dynamicString);
// -> " ... but it will be in <span class='highlight'>real</span> life.";

2 个答案:

答案 0 :(得分:9)

您使用正则表达式捕获组和反向引用来捕获匹配并将其插入字符串

var searchRegex = new RegExp('('+userInput+')' , 'ig');
dynamicString = dynamicString.replace(searchRegex, '<span class="highlight">$1</span>');

FIDDLE

答案 1 :(得分:0)

您也可以使用它而无需捕获组。

dynamicString = text.replace(new RegExp(userInput, 'ig'), '<span class="highlight">$&</span>');