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.
You have to use RegExp : str. match(new RegExp(pattern1+'|'+pattern2, 'gi'));
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With