November 2nd, 2005

Dynamic Regular Expressions

Regular Expressions are cool. They’re basically a special type of search string used by UNIX and a variety of programming languages such as Perl, PHP and JavaScript. I mainly use them in JavaScript to find and replace all instances of a specific string in another string.

Just recently I had to switch all backslashes to forward slashes in a URL. Then yesterday I had a list stored in a string separated by semi-colons and I had to remove a specific list item based on an user interaction. I needed a dynamic regular expression.

Dynamic regular expressions are different in JavaScript. You can’t create an expression in the replace method of a string. You need to create a regular expression object with your expression.

var myString = "My truck is a real old truck.";
var temp = new RegExp("truck","g");

myString = myString.replace(temp, "car");

In the preceding code I replaced every instance of “truck” with “car” globally, that’s what the g parameter is for. But since I used the regular expression object, I can easily swap out the hard coded string for a variable or expression.

Since regular expressions can be somewhat confusing, even to me, I plan on making a quick reference sheet soon. Oh and I plan on sharing it.