Reputation: 194
I am trying to wrap the dynamic insensitive string in span tag but $1 is coming in output. Please help me.
function focusSearchValue(data, value){
var regEx = new RegExp((value), "ig");
data = data.replace(regEx, "<span class=''>$1</span>");
console.log(data);
}
focusSearchValue('SharePoint 2016, Team Collaboration Software Tools', 'sharepoint');
Upvotes: 4
Views: 79
Reputation: 644
I find this syntax to be a little more intuitive, passing a function in as the second argument of replace
(more info: function as argument, regex escaping search terms):
const reEscape = searchTerm => (
searchTerm.replace(/[-{}()[/*+?.^$|\]\\]/g, "\\$&")
);
const addSpan = $1 => `<span>${$1}</span>`;
const focusSearchValue = (data, value) => {
const regex = new RegExp(`${reEscape(value)}`, 'ig');
return data.replace(regex, addSpan);
};
console.log(focusSearchValue('SharePoint 2016, Team Collaboration Software Tools', 'sharepoint'));
Upvotes: 0
Reputation: 626758
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, '\\$&')
.
Upvotes: 2