Thursday, March 27, 2008

Generating regular expression at runtime in javascript

I have never been good with regular expressions. I normally search for the regular expressions online and use it, I can never seem to get them into my brains. Lately I've been working on things where I've had to generate a regular expression at runtime. It is a trivial thing but I was unable to find it when I look for it. So in case you are looking for generating a regular expression at runtime this code snippet might help you out.

var data = "This is a string and I want to replace all the a's";
var re = new RegExp("a", "ig");
alert(data.replace(re, "m"));

This post is more like a reminder for me.

No comments: