function highlight(text) {
var result = [];
for (var i = 0; i < text.length; i++) {
if (text[i] === '"') {
var stop = text.indexOf('"', i + 1);
result.push('<span class="a">');
result.push(text.substring(i, stop+1));
result.push('</span>');
i = stop;
}
else if (text[i] === '*') {
var stop = text.indexOf('*', i + 1);
result.push('<span class="b">');
result.push(text.substring(i, stop+1));
result.push('</span>');
i = stop;
}
else if (text[i] === '<') {
// Skip simple HTML tags.
var stop = text.indexOf('>', i + 1);
result.push(text.substring(i, stop+1));
i = stop;
}
else {
result.push(text.substring(i,i+1));
}
}
return result.join('');
}
例子:
>>> highlight('foo *bar"baz"qux* "foobar" qux')
"foo <span class="b">*bar"baz"qux*</span> <span class="a">"foobar"</span> qux"
或者使用正则表达式:
function highlight2(text) {
return text.replace(/([*"]).*?\1|<[^<>]*>/g, function (match, ch) {
// 'match' contains the whole match
// 'ch' contains the first capture-group
if (ch === '"') {
return '<span class="a">' + match + '</span>';
}
else if (ch === '*') {
return '<span class="b">' + match + '</span>';
}
else {
return match;
}
});
}
正则表达式([*"]).*?\1包含以下内容:
[*"]匹配*或". (他们不需要在里面逃脱[ ])。
( )将匹配的字符串捕获到捕获组 1。
.*?匹配任何东西,直到第一个......
\1匹配捕获到捕获组 1 中的相同字符串。
|是“或”。它尝试匹配左侧,如果失败,它尝试匹配右侧。
<[^<>]*>匹配简单的 html-tags。它将无法处理带有文字<或>其中的属性:(<a href="info.php?tag=<i>">无论如何这都是糟糕的 HTML,但有些浏览器会接受它。)
如果它与 HTML 标记匹配,则ch参数将为undefined,并且else将选择 -branch。
如果要添加更多字符,只需将它们放在 中[ ],然后添加一个 if 语句来处理它们。您可以使用除 , 之外的任何字符-,\并且]无需转义它们。要添加这些字符,您需要\在它们前面放置另一个字符。