www.webdeveloper.com
Results 1 to 3 of 3

Thread: [RESOLVED] Strange Regexp's test method return results

  1. #1
    Join Date
    Oct 2012
    Location
    Croatia
    Posts
    255

    resolved [RESOLVED] Strange Regexp's test method return results

    Can someone explain to me how is this possible?

    When I define global attribute for RegExp pattern, regexp's test method after each true returns false when testing arrays element. When testing string literal returned value is true with the same regexp pattern?

    Here's sample code:

    Code:
    <!DOCTYPE HTML>
    <html>
    <head>
    	<title> Untitled </title>
    	<meta charset="utf-8">
    	<script>
    		var myarray = ["xxx","xxx","xxx","xxx"];
    		var re = new RegExp("xxx");
    		var re2 = new RegExp("xxx","g");
    		
    		for (i = 0; i < myarray.length; i++)
    		{
    			alert(re.test(myarray[i])); //this one returns ture for each array's element as expected
    		}
    		
    		for (i = 0; i < myarray.length; i++)
    		{
    			alert(re2.test(myarray[i])); //this one returns false for every second element
    		}
    		
    		var s = "xxx";
    		alert(re2.test(s)); //returns true
    	</script>
    </head>
    <body>
    </body>
    </html>
    Thanks in advance!

  2. #2
    Join Date
    Mar 2007
    Location
    U.K.
    Posts
    1,127
    Using the g flag sets the lastIndex property

    Code:
        <script>
            var myarray = ["xxx","xxx","xxx","xxx"];
            var re = new RegExp("xxx");
            var re2 = new RegExp("xxx","g");
            
            for (i = 0; i < myarray.length; i++)
            {
                alert(re.test(myarray[i])); //this one returns ture for each array's element as expected
            }
            
            for (i = 0; i < myarray.length; i++)
            {
                alert(re2.test(myarray[i])); //this one returns false for every second element
                re2.lastIndex = 0;
            }

  3. #3
    Join Date
    Oct 2012
    Location
    Croatia
    Posts
    255
    Thanks for the reply, didn't know this.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles