Regular Expression (Regex)

JavaScript: Regular Expression (Regex)

Use a variable in a regular expression

var replace = "regex\\d";
var re = new RegExp(replace,"g");
"mystring1".replace(re, "newstring");

Highlight Text

function highlight(original_text, highlight_text) {
  let regex_highlight = new RegExp(`(${highlight_text})`, "gi");

  let final_text = original_text.replace(regex_highlight, `<span class="highlight">$1</span>`);

  return final_text;
}

Online Regex Tool

Test

Visualization

Reference