我想为特定字符串中的匹配单词应用样式(蓝色字体),该字符串可能包含多个单词。该字符串也可以重复相同的单词。
例: String paragraph =“这是将与substring匹配的字符串。匹配的子字符串可以是一个单词或多个单词组成的字符串。”
String matchingString ='string word'
现在我想将蓝色粗体样式应用于段落字符串中字符串和单词的匹配单词。
请你帮我解决一下javascript怎么做?
预先谢谢 罗伯特。
答案 0 :(得分:1)
假设:
<div id="myDiv">This is the string which will be matched against substring. The matching substring can be a single word or multple words composed string.</div>
.some-class{
color: blue;
font-weight: bold;
}
那么你可以这样做来取代单词:
var elem = document.getElementById('myDiv');
var phrase = 'string word';
var regex = new RegExp(phrase.split(' ').join('|'),"gi");
//result => /string|word/g
elem.innerHTML = elem.innerHTML.replace(regex,'<span class="some-class">$&</span>');
答案 1 :(得分:0)
var text = "This is the string which will be matched against substring...";
var search = "string word";
var words = search.split(" ");
for (var i = 0; i < words.length; ++i) {
text = text.replace(words[i], "<span style='color: blue;'>"+words[i]+"</span>");
}
document.write(text);