Björn
Björn

Reputation: 13207

Highlighting variable word in a string using regular expression

var stringToHighlight = [userinput] // may be any string like "foo", "bar" or "."
var stringToBeHighlighted = [any text] // Lorem Ipsum ...

So far I have

var regex = new RegExp(stringToHighlight, "g")                  
var highlightedString = stringToBeHighlighted.replace(regex, "<span class='highlight'>$&</span>")

This doesn't work for the character "." for example, because it is being interpreted as the regular expression metacharacter . but not the actual character "." resulting in all the text being highlighted. How do I exclude those special metacharacters?

Upvotes: 1

Views: 181

Answers (2)

Qtax
Qtax

Reputation: 33908

JS doesn't have any built in function to escape meta characters in regex, but you could use this function (from this answer):

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

Which would be used like so:

var regex = new RegExp(quotemeta(stringToHighlight), "g");

Upvotes: 1

solidau
solidau

Reputation: 4081

You either need to type in an actual regular expression (escape the "." by placing "\" before it) or you can use a function such as http://phpjs.org/functions/strstr:551 to look for a string literal

Upvotes: 0

Related Questions