Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

pass variable to regrex literal notation javascript

// If you want to get ALL occurrences (g), be case insensitive (i), and use boundaries so that it isn't a word within another word ():

re = new RegExp(`${replaceThis}`, 'gi');

// example:

let inputString = "I'm John, or johnny, but I prefer john.";
let replaceThis = "John";
let re = new RegExp(`${replaceThis}`, 'gi');
console.log(inputString.replace(re, "Jack")); // I'm Jack, or johnny, but I prefer Jack.
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #pass #variable #regrex #literal #notation #javascript
ADD COMMENT
Topic
Name
8+9 =