pass variable to regrex literal notation javascript
// CREATE A REGEXP object
var replace = "regex";
var re = new RegExp(replace,"g");
//then use
"mystring".replace(re, "newstring")// 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 (\\b):
re = new RegExp(`\\b${replaceThis}\\b`, 'gi');
// example:
let inputString = "I'm John, or johnny, but I prefer john.";
let replaceThis = "John";
let re = new RegExp(`\\b${replaceThis}\\b`, 'gi');
console.log(inputString.replace(re, "Jack")); // I'm Jack, or johnny, but I prefer Jack.
Also in JavaScript:
- javascript on script loaded
- left_field in jsgrid
- bodyparser
- how to get csrf token in javascript
- jquery get value radio by name
- count value a to b character javascript
- loop through object js
- settimeout in angular
- check if enter key is pressed jquery
- percentage formula in javascript
- ajax call to load a page on scrolling
- p5js check for keyboard keys
- how to find a name of class from page in jquery
- javascript open pdf in new tab
- react redux npm
- prevent specific state redux-persist
- node js find directory change directory
- decet wheter react app in development or production
- angular.min.js version
- javascript remove item onclick
- js is letter
- check if number appears odd number of times in array javascript
- adding event listener keypress event in javascript
- input in node js