Javascript regular expressions
Friday, 1 February 2008
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.
No. 1 — February 1st, 2008 at 11:00 pm
Nice article! I especially “like” the fact that JS allows match sniffing – try to use console.dir(RegExp) with noscript installed 😉
No. 2 — February 2nd, 2008 at 1:35 am
you can also eval a string formated like a regex to pass variables:
var a = ‘/[test]+/’;
alert(eval(a+’i’).exec(‘TeSt’));
No. 3 — February 2nd, 2008 at 1:54 pm
Good stuff Gareth!
@.mario: yeah exactly that was the stuff I needed to wrap my head around. 🙂
No. 4 — February 22nd, 2009 at 10:14 pm
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?
No. 5 — February 23rd, 2009 at 10:29 am
@mar
I think this is what you mean:-
You need to use the RegExp constructor to dynamically create regular expressions.
No. 6 — December 29th, 2009 at 5:08 am
if
var str = “hello [bob] hello hello [bob]!”;
then how to replace “[bob]” with “bob” only through javascript.
Can anyone sovle it?
No. 7 — December 29th, 2009 at 9:23 am
var str = “hello [bob] hello hello [bob]!”;
str=str.replace(/\[bob\]/g,'”bob”‘);