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('');
}
Example:
>>> highlight('foo *bar"baz"qux* "foobar" qux')
"foo <span class="b">*bar"baz"qux*</span> <span class="a">"foobar"</span> qux"
Or with regular expressions:
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;
}
});
}
The regular expression ([*"]).*?\1 contains the following:
[*"] matches * or ". (They don't need to be escaped inside [ ]).
( ) captures the matched string into capture-group 1.
.*? matches anything up until the first...
\1 matches the same string as was captured into capture-group 1.
| is "Or". It tries to match the left side, and if that fails, it tries to match the right side.
<[^<>]*> matches simple html-tags. It will not be able to handle attributes with literal < or > in them: <a href="info.php?tag=<i>"> (that is bad HTML anyway, but some browsers will accept it.)
In the case when it matches an HTML tag, the ch parameter will be undefined, and the else-branch will be picked.
If you want to add more characters, just put them inside the [ ], and add an if-statement to handle them. You can use any character except -, \ and ] without escaping them. To add those characters, you need to put another \ in front of them.