/    Sign up×
Community /Pin to ProfileBookmark

[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 [I]true[/I] returns [I]false[/I] when testing arrays element. When testing string literal returned value is [I]true[/I] 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>
[/code]

Thanks in advance!

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@Logic_AliNov 07.2013 — Using the g flag sets the lastIndex property

<i>
</i> &lt;script&gt;
var myarray = ["xxx","xxx","xxx","xxx"];
var re = new RegExp("xxx");
var re2 = new RegExp("xxx","g");

<i> </i> for (i = 0; i &lt; myarray.length; i++)
<i> </i> {
<i> </i> alert(re.test(myarray[i])); //this one returns ture for each array's element as expected
<i> </i> }

<i> </i> for (i = 0; i &lt; myarray.length; i++)
<i> </i> {
<i> </i> alert(re2.test(myarray[i])); //this one returns false for every second element
[COLOR=#0000ff][B] re2.lastIndex = 0;[/B][/COLOR]
}
Copy linkTweet thisAlerts:
@tech_soul8authorNov 07.2013 — Thanks for the reply, didn't know this.
×

Success!

Help @tech_soul8 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...