Max*_*Max 0 javascript regex string
我想找到一个高效且优雅的解决方案来解决这个问题:
我需要通过已替换的函数替换字符串的子字符串,不区分大小写.
示例:
var highlight = function(inputString, filterString) {
var regex = new RegExp(filterString, 'gi');
return inputString.replace(regex, '<b>' + filterString + '</b>');
};
highlight('The input', 't');
Run Code Online (Sandbox Code Playgroud)
如果你在浏览器控制台中运行它,你会得到:
"<b>t</b>he inpu<b>t</b>"
Run Code Online (Sandbox Code Playgroud)
我的问题是我想保留替换字符串的原始情况.因此,预期结果将是:
"<b>T</b>he inpu<b>t</b>"
Run Code Online (Sandbox Code Playgroud)
任何的想法 ?
编辑:回复@georg:
return inputString.replace(regex, '<b>$&</b>');
只需使用$&替换,这意味着"找到了什么":
var highlight = function(inputString, filterString) {
var regex = new RegExp(filterString, 'gi');
return inputString.replace(regex, '<b>$&</b>');
};
x = highlight('The input', 't');
document.write("<pre>" + JSON.stringify(x,0,3)); Run Code Online (Sandbox Code Playgroud)
其他$...魔法构造,供参考:

| 归档时间: |
|
| 查看次数: |
62 次 |
| 最近记录: |