1

我想为可能包含多个单词的特定字符串中的匹配单词应用样式(蓝色字体)。该字符串也可以重复相同的单词。

例如:字符串段落=“这是将与子字符串匹配的字符串。匹配的子字符串可以是单个单词或多个单词组成的字符串。”

字符串匹配String = '字符串单词'

现在我想将蓝色粗体样式应用于字符串和段落字符串中单词的匹配单词。

你能帮我看看如何通过javascript做到这一点吗?

提前感谢罗伯特。

4

2 回答 2

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>');

现场演示

于 2012-07-28T13:00:18.253 回答
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);

在这里测试它:http: //jsfiddle.net/Zh6t9/

于 2012-07-28T12:58:27.027 回答