1
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?

1

2 Answers 2

1

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");
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.