Javascript regular expressions

Back to articles

hackvertor

Author:

Gareth Heyes

@hackvertor

Published: Fri, 01 Feb 2008 22:27:16 GMT

Updated: Sat, 22 Mar 2025 15:38:09 GMT

Ronald and I had a good conversation about Javascript regular expressions comparing them to PHP. He was having difficultly with the syntax because he was used to preg in PHP so I promised to share my knowledge gained from developing various online scripts.

First up preg_match in PHP can be achieved using the match function in Javascript, they are both very similar but it's just a matter of getting your head round the different syntax. Match is part of the String object and here is how to use it:-

<pre lang="javascript"> alert('Test'.match(/[a-z]/)) </pre>

You can match subpatterns like this (I've tried to keep it close to PHP syntax as possible):-

<pre lang="javascript"> pattern = /([a-z]+)([0-9]+)([A-Z]+)/; subject = 'test1234TEST'; matches = subject.match(pattern); match1 = matches[1]; match2 = matches[2]; match3 = matches[3]; alert(match1); alert(match2); alert(match3); </pre>

You can also create matches using the RegExp object, this is useful for passing variables into the pattern which to my knowledge isn't possible with "//" syntax.

<pre lang="javascript"> a = 'a+'; alert(new RegExp(a).exec('123aaaabcdef')); </pre>

The exec method can also be called from "//" patterns.

<pre lang="javascript"> alert((/[0-9]+/).exec('12345abcdef')) </pre>

Javascript supports the modifiers "g", "i" and "m", here's how to use them with "//" syntax:-

<pre lang="javascript"> matches = 'ababababababa'.match(/[a]/g); alert(matches); alert(matches.length); </pre>

Here's how to use modifiers with the RegExp object:-

<pre lang="javascript"> alert(RegExp('[test]+','i').exec('TeSt')) </pre>

Ok I hope you're following so far, I'm going to move onto replace now and how to use the various combinations.

Here's how to use replace, notice how only one "t" is replaced:-

<pre lang="javascript"> str = 'test'; alert(str.replace('t','x')) </pre>

In order to match more than one instance of the string and use a regular expression you have to do the following:-

<pre lang="javascript"> alert('test'.replace(/t/g,'x')) </pre>

Javascript also supports anonymous functions within replace which is really powerful, you can even nest the replaces and perform other logic:-

<pre lang="javascript"> alert('teeest'.replace(/e+/g, function(str) { return str.replace(/e/g,'x'); })); </pre>

You can also use parenthesis with replace and match the subpatterns like this:-

<pre lang="javascript"> alert('567'.replace(/([0-9])([0-9])([0-9])/,'$3$2$1')); </pre>

That's all for now I may follow up this article at a later date when I have some spare time, I hope you enjoyed it.

Back to articles