Javascript regular expressions

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:-

alert('Test'.match(/[a-z]/|>))

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

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

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.

a = 'a+';
alert(new RegExp(a).exec('123aaaabcdef'));

The exec method can also be called from “//” patterns.

alert((/[0-9]+/|>).exec('12345abcdef'))

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

matches = 'ababababababa'.match(/[a]/g|>);
alert(matches);
alert(matches.length);

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

alert(RegExp('[test]+','i').exec('TeSt'))

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:-

str = 'test';
alert(str.replace('t','x'))

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

alert('test'.replace(/t/g,'x'))

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

alert('teeest'.replace(/e+/g, function(str) {
  return str.replace(/e/g,'x');
}));

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

alert('567'.replace(/([0-9])([0-9])([0-9])/|>,'$3$2$1'));

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.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Slashdot
  • StumbleUpon

Comments 3

  1. .mario wrote:

    Nice article! I especially “like” the fact that JS allows match sniffing - try to use console.dir(RegExp) with noscript installed ;)

    Posted 01 Feb 2008 at 11:00 pm
  2. riahmatic wrote:

    you can also eval a string formated like a regex to pass variables:

    var a = ‘/[test]+/’;
    alert(eval(a+’i').exec(’TeSt’));

    Posted 02 Feb 2008 at 1:35 am
  3. Ronald wrote:

    Good stuff Gareth!

    @.mario: yeah exactly that was the stuff I needed to wrap my head around. :)

    Posted 02 Feb 2008 at 1:54 pm

Post a Comment

Your email is never published nor shared. Required fields are marked *

Comment spam protected by SpamBam