Alex Rivera | Logout

Javascript String.replace with dynamic regular expressions?

Asked 2009-07-31T22:23:53.100
35

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>");
Edit
Report

1 Answer

38

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
answered 2011-01-21T11:27:44.833

Your Answer