【发布时间】:2013-12-28 21:24:49
【问题描述】:
我们有一个字符串:
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.";
【问题讨论】:
-
你试过userInput.toLowerCase()...
-
不行,因为如果用户搜索1366 Mulberry Lane,那么匹配结果将显示全部小写,而应该是正确大小写。
标签: javascript regex