0

I am attempting to find a sentence in a paragraph (contained in a textarea), and highlight it. All works well if the sentence does NOT contain opening and closing parenthesis, such as the example below. The replace method is unable to replace the string with its equivalent surrounded by the "mark" tags. Can anyone advise how I can update my Regex to find and replace a string containing parentheses? Do I need to find and replace all parentheses with "/(" and "/)" first?

const text = "An economy is composed of suppliers (workers) and demanders (firms)."

const regex = new RegExp(text, "\d");
// regex returns: /The market for labor, then, is composed of suppliers (workers) and demanders (firms). /
        console.log("REGEX:", regex);
        let match = text.replace(regex, "<mark>$&</mark>");
        console.log("MATCH:", match);
tlockhart
  • 381
  • 2
  • 7
  • What is your goal here and what is the actual expected output? – Tim Biegeleisen Mar 29 '22 at 07:01
  • 2
    `new RegExp(text, "\d");` - this is completely wrong. `text` must be actual regex and second argument is flags, not regex. – Justinas Mar 29 '22 at 07:02
  • 1. You can use `\(` and `\)` for literal parentheses characters instead of regex groups. You also need to escape the `.` at the very end with `\.` as it has a special meaning 2. text.replace (and text.replaceAll) can work with string rather than regex 3. You can write a function to convert plain text to escaped version for regex, as shown in this thread: https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript – qrsngky Mar 29 '22 at 07:04
  • @qrsngky, that worked perfectly. This solved my issue. – tlockhart Mar 29 '22 at 19:24

1 Answers1

0

Highlight Text in Parenthesis

html:

<html>
  <body>
   <p id="txt">"(An economy is composed of suppliers (workers) and demanders (firms).)</p>
  </body>
</html>

JS:

function hilitetext() {
  const s = document.getElementById("txt").textContent;
  const regex = /(?:^[^(]?[^(]+)?(\(\w+\))/g;//retains parenthesis
  //const regex = /(?:^[^(]?[^(]+)?\((\w+)\)/g;//removes parenthesis
  document.getElementById("txt").textContent = s.replace(regex, "<mark>$1</mark>");
}
Cooper
  • 59,616
  • 6
  • 23
  • 54