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.

7 Responses to “Javascript regular expressions”

  1. .mario writes:

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

  2. riahmatic writes:

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

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

  3. Ronald writes:

    Good stuff Gareth!

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

  4. Mar canet writes:

    I don’t know how to add a variable string this remplace and regular expresion function.

    var str = “hello bob hello hello bob!”;
    var s = “bob”;
    alert( str.replace(/s/+/g, function(str) { return str.replace(/s/g,’yes’);}) );

    could you show how to do it?

  5. Gareth Heyes writes:

    @mar

    I think this is what you mean:-

    var str = "hello bob hello hello bob!";
    var s = "bob";
    alert( str.replace(new RegExp(s,'g'), function(str) { return 'yes';}));
    

    You need to use the RegExp constructor to dynamically create regular expressions.

  6. Manish writes:

    if
    var str = “hello [bob] hello hello [bob]!”;
    then how to replace “[bob]” with “bob” only through javascript.
    Can anyone sovle it?

  7. Gareth Heyes writes:

    var str = “hello [bob] hello hello [bob]!”;
    str=str.replace(/\[bob\]/g,'”bob”‘);