I'm developing in VS2005 and have some JS code in my page. I have set a breakpoint during a particular loop where I was having an issue. Here is my little conversation with the IDE--
? ind
/d/g
? ind.test("d")
true
? ind.test("dtn")
false
? ind.test("dtn")
true
? ind.test("dtn")
false
? ind.test("dtn")
true
? ind.test("dtn")
false
Why is the test alternating between true and false? ind
is my RegEx - I set it like this:
case "datetime" : ind = new RegExp("d","g");break;
UPDATE
So I've solved my issue by changing my declaration to
ind = /d/;
ie omitting the global modifier. I suppose that
ind = RegExp("d");
would work equally as well.
The question remains though. Why was the global modifier causing the test
to alternate between true an开发者_运维问答d false?
As with exec (or in combination with it), test called multiple times on the same global regular expression instance will advance past the previous match.
Source: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp/test
So what exactly happens here is that since you're using the global option for the regex, it will continue to search the string after it found an match.
ind.test("d")
This will find d at position 0.
ind.test("d")
This will now search for d starting at position 1, but since that's the end of the string it will not find anything therefore returning false.
We can use the lastIndex
property of the regex to proof that:
ind.lastIndex
>> 0
ind.test("d")
>> true
ind.lastIndex
>> 1
ind.test("d")
>> false
Calling re.test(str)
is equivalent to re.exec(str) != null
(see specification of RegExp.prototype.test(string)
).
And when calling exec
on a regular expression with g modifier repeatedly, the search is not started at the begin of the string but at the position of where the previous search ended (lastIndex
, initialized with 0
):
If your regular expression uses the "
g
" flag, you can use theexec
method multiple times to find successive matches in the same string. When you do so, the search starts at the substring ofstr
specified by the regular expression'slastIndex
property (test
will also advance thelastIndex
property).
That’s why you’re getting this odd result.
精彩评论