Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript String.replace with dynamic regular expressions?

People also ask

Can I use regex in replace?

How to use RegEx with . replace in JavaScript. To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring.

Which of the following options can you use to create a dynamic regex using the string in a variable?

You have to use RegExp : str. match(new RegExp(pattern1+'|'+pattern2, 'gi'));

Does JavaScript have replaceAll?

replaceAll() The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function to be called for each match.


You can make a regular expression object from a string using the RegExp constructor function:

var regExp = new RegExp(myString);  // regex pattern string

text.replace(regExp, '');

Addition to CMS: The RegExp constructor has an second optional parameter flags
(15.10.4 The RegExp Constructor)

var text = "This is a Test.";

var myRegExp = new RegExp('teST','i');

text.replace(myRegExp,'Example');
// -> "This is a Example."

as Flags you can set

  • g -> global search (all occurrences)
  • i -> case insensitive
  • m -> multiline

var value = "2012-09-10";
value = value.replace(/([0-9]{4})[\/-]([0-9]{2})[\/-]([0-9]{2})/,"$3/$2/$1");
alert(value);

this will show

10/09/2012