1
highlightStr: function (body, searchString){
    console.log(searchString);
    var regex = new RegExp('(' + searchString + ')', 'gi');
    console.log(regex)
    return body.replace(regex, "<span class='text-highlight'>$1</span>");
}

Above is the code I'm using. I want to find and replace the searchString, which could be anything. It works fine for most words, but fails when finding words with apostrophes.

How can I modify the regex to include special characters like the appostrophe.

var body = "<br>I like that Apple&#x2019;s.<br>";
var searchString = "Apple's";

Thank you

  • Do you mean you want `var regex = new RegExp(searchString + "(?:'s)?", "gi");`? Note you do not need the outer parentheses. Besides, it is a good idea to [*escape*](https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript) the `searchString`. – Wiktor Stribiżew Apr 24 '18 at 19:32
  • Possible duplicate of [Is there a RegExp.escape function in Javascript?](https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript) – Alexis Wilke Apr 24 '18 at 19:35
  • It works just fine - https://jsfiddle.net/0jgsayk9/ – Rahul Desai Apr 24 '18 at 19:39
  • Sorry, I was unclear about the problem. I rewrote the issue. –  Apr 24 '18 at 20:22

1 Answers1

0

You should escape the search string to make sure the regex works OK even if the search string contains special regex metacharacters.

Besides, there is no need wrapping the whole pattern with a capturing group, you may always reference the whole match with $& placeholder from the replacement pattern.

Here is an example code:

var s = "I like that Apple's color";
var searchString = "Apple's";
var regex = new RegExp(searchString.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), "gi");
document.body.innerHTML = s.replace(regex, '<b>$&</b>');
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • I tried this. It will find and replace "Apple" with highlighted. But, doesn't work for "Apple's" –  Apr 24 '18 at 20:24
  • @JasonGelinas It is still unclear. What value holds `Apple's`? What is the input string? What is the expected result? You can see that my `searchString` holding `children` finds and replaces `Children's`. – Wiktor Stribiżew Apr 24 '18 at 20:25
  • The searchString = "Apple's". The body = "I like that Apple's color". –  Apr 24 '18 at 20:27
  • See update: it works. Now your question sounds much more unclear than at the beginning though. – Wiktor Stribiżew Apr 24 '18 at 20:29
  • I found out why it wasn't working on my end. In the body, the apostrophe is escaped. So it's not "Apple's" instead, it's "Apple’s". Any ideas on how to modify the regex to pick this up? –  Apr 24 '18 at 20:42
  • @JasonGelinas You should perform the search and replace on plain text, not its entitized representation. Else, entitize the search string, too. – Wiktor Stribiżew Apr 24 '18 at 20:52