views:

51

answers:

3

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 other 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.

+2  A: 

How about using a highlight plugin?

The MYYN
That's a fine plugin and I've used it; it doesn't allow regexes but that may be OK for the original question.
Pointy
+2  A: 

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.

Frxstrem
Thanks, that first link was exactly what I needed.. I've added it to my growing library of utility functions.
Mike
+3  A: 

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, '\\$&')
};
bobince
The input is a string, not HTML. I'm only returning HTML.
Mike
Then what if the string contains HTML-special characters? Again, cross-site-scripting.
bobince