The parentheses around value
are not part of the pattern, and thus, your regex has no capturing group defined, that $1
could refer to from the string replacement pattern. That is why $1
is passed as a literal string as the replacement result.
You need to use $&
to refer to the whole match (see String#replace
"Specifying a string as a parameter" section), and return the string:
function focusSearchValue(data, value){
var regEx = new RegExp(value.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), "ig");
return data.replace(regEx, "<span class=''>$&</span>");
}
console.log(focusSearchValue('SharePoint 2016, Team Collaboration Software Tools', 'sharepoint'));
Since you pass a variable to the regex engine that should be parsed as a literal string, it is advisable to escape all special chars that may act as special regex metacharacters, hence the added escaping .replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
.