Skip to content Skip to sidebar Skip to footer

Wrap Dynamic Insensitive String In Span Tag

I am trying to wrap the dynamic insensitive string in span tag but $1 is coming in output. Please help me.

Solution 1:

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:

functionfocusSearchValue(data, value){
        var regEx = newRegExp(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, '\\$&').

Solution 2:

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):

constreEscape = searchTerm => (
  searchTerm.replace(/[-{}()[/*+?.^$|\]\\]/g, "\\$&")
);

const addSpan = $1 => `<span>${$1}</span>`;

constfocusSearchValue = (data, value) => {
  const regex = newRegExp(`${reEscape(value)}`, 'ig');
  return data.replace(regex, addSpan);
};

console.log(focusSearchValue('SharePoint 2016, Team Collaboration Software Tools', 'sharepoint'));

Post a Comment for "Wrap Dynamic Insensitive String In Span Tag"