View Full Version : Javascript RegEx.exec Array behaving in VERY peculiar way

Duke Leto
05-23-2006, 05:12 PM
I'm trying to use a regular expression to return an array of names entered into a text input.

I'm going to post the code and try to explain what's happening.

var basicRegExMatch = new RegExp("[a-z0-9]+","gi");
var arrNames = new String();

function OhFunctionMyFunction()

var Name1;
var Name2;
var Name3;
var inputName = 'ab,cde,gf';

alert('Original String: ' + inputName);

if (inputName.length = 0) {
return false;

arrNames = basicRegExMatch.exec(inputName);

if (arrNames != null) {
alert('Element 1: ' + arrNames[0]);
alert('Element 2: ' + arrNames[1]);
alert('Element 3: ' + arrNames[2]);
switch (arrNames.length) {
case 1:
Name1 = arrNames[0];
Name2 = "";
Name3 = "";
case 2:
Name1 = arrNames[0];
Name2 = arrNames[1];
Name3 = "";
Name1 = arrNames[0];
Name2 = arrNames[1];
Name3 = arrNames[2];


What OUGHT to happen is that the input string should be split into an array of words:


What is actually happening is that the first time the function is run, it returns a 1 element array with "ab". The second time it gets run, it returns a 1 element array containing "cde". :eek: :eek: :eek:

If you change the input to just "ab". You get back "b" pretty consistently.

I'm utterly confused by this behavior, which runs contrary to all my experience with Perl and VB.

What aren't I understanding?

05-23-2006, 07:15 PM
you can split a string into an array on a word break :
var A=str.split(/\b/)
or the non digits and numbers :

var A=str.split(\W+);

You can return an Array using match:

var A= str.match(/\b([a-z][\w\.\- ])+\b);
//includes hyphenated names,O'toole and Mr. Jones

If you insist on using RegExp you need to run it in a loop.
Each iteration that does not return null returns an array of the
matched substrings and sets the lastIndex to the end of the match.

But you haven't set any substrings (with parenthesis) to match:
var basicRegExMatch =/\b([a-z0-9])+/g

Duke Leto
05-23-2006, 08:19 PM
OK, but as I say, the behavior is very non-Analagous to Perl and VB. Thank you very much!

05-24-2006, 08:04 AM
Duke Leto: RegExp.prototype.exec always returns a special regex array for a single regex match. The array will have member 0 as the match for entire pattern , and all captured subpatterns will follow in members 1 and up. It will also have the member input containing the entire match, and the member index containing the index in the input string where the pattern match started.

String.prototype.match returns the same as RegExp.prototype.exec, except if the global flag is set.
If the global flag is set, it will return an array of full pattern matches.

As thus String.prototype.match could be said to be the opposite of String.prototype.split if the global flag is set.

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum