-1

I have an application that matches certain words in long paragraphs.

The word can sometimes find it without an apostrophe, for example = "cant", but cannot find it when written as "can't" in a paragraph. So it can't match, how can i solve it?

There is only one of the apostrophes in the link below, but I also encounter this problem if there are sentences with = [' " ‘ ’] marked.

https://regex101.com/r/tsYuLH/1

my code block that matches words in paragraph:

this.highlightedText is my paragraph and element is my word that needs to be matched in the paragraph (I'm putting it in my span tag that I gave the background color, so it's matched.)

this.highlightedText = this.highlightedText.replace(new RegExp(element.split(".").join("\\.").split("+").join("\\+"), "g"),
                `<span>${element}</span>`);

long story short, even if all the apostrophes of the regex I wrote come up, I expect my word to match.

greJuva
  • 21
  • 4

1 Answers1

0

If you know the words you want to highlight in advance, you can brute force the result by special regex which accepts 0 or 1 apostrophes after each character.

  const myWord = "Emek Sahnesinde"
  let extraWord = "";

  for (const character of myWord) {
    extraWord += character + `'?`
  }

  const regex = new RegExp('('+extraWord+')')

  this.highlightedText = this.highlightedText.replace(regex,`<span>${element}</span>`);

  "Emek Sahnesinde".match(regex) // True
  "E'mek Sa'hnes'inde".match(regex) // True
  "Something else".match(regex) // False
Wandrille
  • 6,267
  • 3
  • 20
  • 43
  • Sorry i couldn't understand this solution. Yes I know the words to be highlighted before, but I couldn't integrate the code you wrote into my system, probably not your problem. – greJuva Apr 18 '23 at 15:20
  • I have updated the code to match your need @greJuva – Wandrille Apr 18 '23 at 15:43
  • Thank you, when I scanned the code with debug, I understood what you mean. @Wandrille – greJuva Apr 18 '23 at 16:03