Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 929
Mike Christensen Avatar asked Sep 01 '10 19:09

Mike Christensen


People also ask

How do you highlight selected text in JavaScript?

getSelection() Method in JavaScript. The window. getSelection() method in JavaScript allows us to get the text highlighted or selected by the user on the screen. This method returns an object that contains information related to the text highlighted on the screen.

How do you highlight text in search?

The 'mark' tag If you surround any text inside of the mark tag, it will automatically get highlighted by the browser in this striking yellow color. That makes highlighting searched text quite a simple task then.


1 Answers

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.

like image 176
Frxstrem Avatar answered Nov 09 '22 22:11

Frxstrem