RegExp.test

K

Karel Miklav

If I test() string two times in a row like:

var re = new RegExp(expression, "gi");
re.test(s1);
re.test(s1);

only the first test passes. Is this normal?
 
L

Lasse Reichstein Nielsen

Karel Miklav said:
If I test() string two times in a row like:

var re = new RegExp(expression, "gi");
re.test(s1);
re.test(s1);

only the first test passes. Is this normal?

Yes.

When you give the "g" option on a regular expression, it is able
to be matched several times against a string, each starting only at
the end of the previous match. Only when the regular expression
fails to match is the starting index reset to zero. It works like
this when calling "exec" on the regular expression, and "test" is
defined in terms of "exec".

Calling "match" on the string instead will do all the matches in one
round, similar to the example below.

Example:
---
function allMatches(re, string) {
var match, result = [];
while((match = re.exec(string))) {
result.push(match[0]);
}
return result;
}

alert(allMatches(/a\w/g,"banananasandapplesauce"));
 
J

Janwillem Borleffs

Lasse said:
When you give the "g" option on a regular expression, it is able
to be matched several times against a string, each starting only at
the end of the previous match. Only when the regular expression
fails to match is the starting index reset to zero. It works like
this when calling "exec" on the regular expression, and "test" is
defined in terms of "exec".

Or you set re.lastIndex to 0 before calling re.test() again.


JW
 
K

Karel Miklav

Janwillem said:
Lasse Reichstein Nielsen wrote:
Or you set re.lastIndex to 0 before calling re.test() again.

Phew, didn't know about this. Thank you.
 
K

Karel Miklav

Janwillem said:
Lasse Reichstein Nielsen wrote:
Or you set re.lastIndex to 0 before calling re.test() again.

Phew, didn't know about this. Thank you.
 
K

Karel Miklav

Janwillem said:
Lasse Reichstein Nielsen wrote:
Or you set re.lastIndex to 0 before calling re.test() again.

Phew, didn't know about this. Thank you.
 
K

Karel Miklav

Janwillem said:
Lasse Reichstein Nielsen wrote:
Or you set re.lastIndex to 0 before calling re.test() again.

Phew, didn't know about this. Thank you.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top