I am building a highlight feature for search results on my website and need to escape the user's input so that I could highlight the matching string within the original text.
The function
function sanitize_for_regex(s){
var escaped = '';
for(var i = 0; i < s.length; ++i){
switch(s[i]){
case '{':
case '}':
case '[':
case ']':
case '-':
case '/':
case '\\':
case '(':
case ')':
case '*':
case '+':
case '?':
case '.':
case '^':
case '$':
case '|':
escaped+= '\\';
default:
escaped+= s[i];
}
}
return escaped;
}
How it's used
var input_from_user = 'Hey + wi$ll th<is \'" { tex|t / \\ mess w?>ith you?';
var highlighted_text = original_text.replace(new RegExp('('+sanitize_for_regex(input_from_user)+')', 'gi'), '<span style="background-color:#FBFB73;">$1</span>');
My test cases show that it's working quite well but I would like to get some feedback from other professionals.
Does this function look like it will escape all injection "attempts"? (I quoted attempts because the user is usually not aware of attempting to break anything)
Could the performance be improved?
$1
. There are comments on the answer that explain the second replace. And that's a good rule of thumb, but time spent deciphering regexes is the price you pay for getting good at them. \$\endgroup\$replace(/\x08/g, '\\x08')
section, wouldn't the additional and potentially unnecessary regex matching cause a decrease in the performance which Google is so keen on achieving? \$\endgroup\$