0

Possible Duplicate:
Why RegExp with global flag in Javascript give wrong results?

I have the following method to which I'm passing these parameters:

var stringValue = "50, abc";
var stringArray = stringValue.split(",");
var agePattern = /^([0-9]|[1-9][0-9]|[1][0-4][0-9]|[1][5][0])$/g;

age = getMatchingString(stringArray, agePattern);

//---------------------------------------------

function getMatchingString(stringArray, regexPattern) {
    //alert("getMatchingString");
    for (var i=0; i < stringArray.length; i++) {
        if (regexPattern.test(stringArray[i])) {

            return (stringArray[i].match(regexPattern)).toString();

        }
    }

    return null;
}

Chrome shows the following funny behavior where test method with stringArray[i] and stringArray[0] show different values even when i = 0 as shown in the image:

Demonstration of the problem

Can someone explain this to me please?

Community
  • 1
  • 1

1 Answers1

1
var stringValue = "50, abc";
var stringArray = stringValue.split(",");
var age = getMatchingString(stringArray);

function getMatchingString(stringArray)
{
    var len=stringArray.length;
    for (var i=0; i < len; i++)
    {
        if(!isNaN(stringArray[i]))
        {
           return stringArray[i]
        }
    }

    return null;
}

alert(age)//50

Perhaps, if you are looping through the array to check for the existence of a numeric value as such age, isNaN is much better a option to use here than using a regex pattern.

DEMO

spaceman12
  • 1,039
  • 11
  • 18