开发者

Javascript Regular Exception Matching a String Once Every Two Attempts in Chrome and Firefox

开发者 https://www.devze.com 2023-03-29 14:20 出处:网络
I have the following regular expression in javascript : 开发者_开发知识库var the_regexp = /^\\/([!\\/]*)\\/?(\\w*)\\??([\\=|\\w]*)\\/?$/gi

I have the following regular expression in javascript :

开发者_开发知识库var the_regexp = /^\/([!\/]*)\/?(\w*)\??([\=|\w]*)\/?$/gi

It Firefox and Chrome console, it find a match for the string "/d" once every two attemps.

>the_regexp
/^\/([!\/]*)\/?(\w*)\??([\=|\w]*)\/?$/gi
>the_regexp.exec("/d")
null
>the_regexp.exec("/d")
["/d", "", "d", ""]
>the_regexp.exec("/d")
null
>the_regexp.exec("/d")
["/d", "", "d", ""]

Can somebody explain this behaviour ?


MDN Docs:

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

So when your regex has a g flag, and you use the exec method once, the next time you execute it it will search for a match after the first match. In this case, there is none: exec will return null and the lastIndex property will be reset.

For example:

var str = "abcdef";
//         ^ starting index for search is here
var regex = /ab/g;

regex.exec(str);
// str: "abcdef"
//         ^ starting index for search is now here

regex.exec(str);
// no match found from starting index, return null and reset
// str: "abcdef"
//       ^ starting index reset

I'm sorry for my bad wordings etc, I'm not fully awake...


You might want to remove the g flag from your Regex, depending on what you want to achieve. Also, those empty capturing groups look kind of unnecessary.

EDIT: Looks like Reanimation beat me ;)

0

精彩评论

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