Regular Expression (Regex)
JavaScript: Regular Expression (Regex)
Categories:
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
- javascript - How do you use a variable in a regular expression? - Stack Overflow
- Regular expressions - JavaScript | MDN
- String.prototype.match() - JavaScript | MDN
- String.prototype.replace() - JavaScript | MDN
- highlighting - How to highlight text using javascript - Stack Overflow