Alex
Alex

Reputation:

Javascript String.replace with dynamic regular expressions?

I have the following code, which works, but I need to inject some different stuff into the regular expression object (regex2) at runtime. However, text.replace does not seem to like a string object for the regular expression, so how can I make this work?

var regex2 = /\|\d+:\d+/;
document.write("result = " + text.replace(regex2, '') + "<br>");

Upvotes: 35

Views: 55206

Answers (4)

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

Upvotes: 38

Laussanne Yannick
Laussanne Yannick

Reputation: 39

you can use eval to,

new RegExp( eval("/"+str+"/i") );

bye...

Upvotes: -5

Muhammad Zubair
Muhammad Zubair

Reputation: 61

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

Upvotes: 6

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 827256

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, '');

Upvotes: 70

Related Questions