CODE:
var searchedTerm = "test";
var returnedString = "National testing Plant testers";
var replacedString = returnedString.replace(/\searchedTerm/g, '<span class="highlight">'+searchedTerm+'</span>');
换句话说,我在从返回的较长字符串中替换搜索到的字符串后,突出显示搜索到的字符串与返回的字符串匹配的位置。请记住突出显示它是否在同一个返回的字符串(即全局)中匹配多次。
答案 0 :(得分:1)
使用 RegExp()
将搜索字符串转换为regex
var searchedTerm = "test";
var returnedString = "National testing Plant testers";
var replacedString = returnedString.replace(new RegExp(searchedTerm, 'g'), '<span class="highlight">' + searchedTerm + '</span>');
document.write(replacedString);
.highlight {
color: red;
}