Skip to main content

JavaScript splits & matches with regular expressions (regex)

I had been developing some client-side validation code in jQuery/JavaScript and using Firefox (and the excellent Firebug) to test and debug it. I was then asked to ensure that it worked in IE6 & IE7 and that's when the problems started.

Apart from the usual "which file does that line number equate to, and why does it not tie up?" issues I found that IE doesn't like taking a regular expression as it's parameter to the JavaScript split function. Firefox will happily accept this and works fine but IE doesn't. After some searching it appears that Firefox might be the odd one out and that it's non-standard to pass in a regex.

So what do you do if you want to split up a string based on a regular expression or rather a rule that can't be simply expressed in the way that the split function wants it? Wouldn't it be nice if you could ask if a string matches a regex but then use certain matched bits of the string in your next few lines of code?

Well you can, simply use the match method, surrounding the bits of the regex that you want to use later in parenthesis '(' and ')' and then you can use the global JavaScript variable RegEx to pull them out.

So if 1234-ABC is your text, and you want the numbers as one part and the characters as another then you would use this regular expression to match on: ^([0-9]*)-([A-Z]*)$. You can then get hold of the matched numbers bit with RegEx.$1 and the letters bit with RegEx.$2.
var productCode = "1234-ABC";
productCode.match(/^([0-9]*)-([A-Z]*)$/);
var numbers = RegEx.$1;
var letters = RegEx.$2;
Technorati Tags: , ,

Comments