开发者

Unusual javascript Regex result, explanation please!

开发者 https://www.devze.com 2023-01-25 18:10 出处:网络
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--

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 the exec method multiple times to find successive matches in the same string. When you do so, the search starts at the substring of str specified by the regular expression's lastIndex property (test will also advance the lastIndex property).

That’s why you’re getting this odd result.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号