开发者

Javascript: Highlighting part of a string with <b> tags

I'm trying to highlight a match in a string by inserting <b> tags around the matching substring. For example, if the query is "cat" then:

"I have a cat."

should become:

"I have a <b>cat</b>."

Likewise, if the query is "stack overflow", then:

"Stack Overflow is great."

should become:

"<b>Stack Overflow</b> is great."

In oth开发者_StackOverflow中文版er words, I have to preserve the case of the original string, but not be case-sensitive when matching.

One thing I was trying so far is:

var regex = new RegExp('(' + query + ')', 'i');
return strResult.replace(regex, '<b>$1</b>');

However, this causes a runtime exception if query has any parenthesis in it, and I think it'd be too much hassle to attempt to escape all the possible regular expression characters.


See "Escape Regular Expression Characters in String - JavaScript" for information about how to escape special regex characters, such as ()

EDIT: Also check out this older SO question that asks a very similar - almost identical - question.


Don't use regex to manipulate HTML.

For example if the query is ‘cat’, then:

I have a <em class="category">dog</em>

will become a mess of broken markup. In cases where the query and text may be user-generated, the resulting HTML-injection attacks are likely to leave you with cross-site-scripting security holes.

See this question for an example of how to find and mark up text using a regex in the DOM.

(For completeness, here is a function to escape regex-special characters, since the version linked at snipplr is insufficient. It fails to escape ^ and $, plus - which is special in character groups.)

RegExp.escape= function(s) {
    return s.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')
};


How about using a highlight plugin?

  • http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜