6
var searchText = "hello world";
var searchTextRegExp = new RegExp(searchText , "i"); //  case insensitive regexp
var text = "blahblah Hello Worldz";

text.replace(searchTextRegExp , '<match>' + searchText + '</match>');

我正在尝试改进这段代码。目前,它小写 Hello World,因为它使用 searchText 作为替换值。

我希望只用标签包装 Hello World 而不是修改它的大小写,同时仍然保持不区分大小写的搜索。

有什么好方法可以做到这一点?我相信 string.indexOf 是区分大小写的——我认为这让事情变得更复杂了?

4

3 回答 3

13

在替换文本中,您可以使用$&来引用正则表达式匹配的任何内容。

text = text.replace(searchTextRegExp , '<match>$&</match>');

您还可以使用$1,$2等来引用正则表达式中捕获组的匹配项。

于 2013-08-25T03:17:39.617 回答
1

替换字符串可以包含模式,特别是$&

$&
插入匹配的子字符串。

所以你可以说:

text.replace(searchTextRegExp , '<match>$&</match>').

使用在text.

于 2013-08-25T03:17:54.090 回答
0

你可以不用indexOf正则表达式来做到这一点。怎么样:

var index = text.toLowerCase().indexOf(searchText);
if (index != -1) {
    text = text.substring(0, index - 1) + 
        "<match>" + 
            text.substr(index, searchText.length) + 
        "</match>" + 
        text.substring(index + searchText.length);
 }

小提琴

于 2013-08-25T03:23:59.530 回答