This article is an introduction to the considerations when using Exec for regular expression global matching in Javascript.
Let's take a look at common usage:
Copy Code code as follows:
<script type= "Text/javascript" >
var pattern =/http:\/\/([^\/\s]+)/;
Alert (pattern.exec (' http://www.codebit.cn ')); http://www.codebit.cn,www.codebit.cn
Alert (pattern.exec (' http://YITU.org ')); http://YITU.org,YITU.org
Can also be written directly/http:\/\/([^/]+)/.exec (' http://www.codebit.cn ');
</script>
Next, look at the bizarre events in the global model:
Copy Code code as follows:
<script type= "Text/javascript" >
var pattern =/http:\/\/([^\/\s]+)/g; Using the G modifier
Alert (pattern.exec (' http://www.codebit.cn ')); http://www.codebit.cn,www.codebit.cn
Alert (pattern.exec (' http://YITU.org ')); does not return the desired http://YITU.org,YITU.org, but instead returns a null
</script>
The second statement does not return the desired result, but instead returns NULL because:
In global mode, when exec () finds the text that matches the expression, after the match, it sets the Lastindex property of the regular expression object to the next position in the last character of the text. This means that you can iterate through all the matching text in a string by repeatedly calling the Exec () method. When exec () can no longer find the matching text, it returns null and resets the Lastindex property to 0.
The following are the ways to match the normal global mode:
Copy Code code as follows:
<script type= "Text/javascript" >
var pattern =/http:\/\/([^\/\s]+)/g;
var str = "codebit.cn:http://www.codebit.cn | Yitu.org:http://yitu.org ";
var result;
while (result = Pattern.exec (str))!= null) {
Alert ("Result:" + result + "lastindex:" + pattern.lastindex);
}
result:http://www.codebit.cn,www.codebit.cn lastindex:34
Result:http://yitu.org,yitu.org lastindex:67
</script>
From the code above, we can see that the problem in the second code, the impact factor is lastindex, so we can solve the problem by manually placing lastindex 0.
Copy Code code as follows:
<script type= "Text/javascript" >
var pattern =/http:\/\/([^\/\s]+)/g; Using the G modifier
Alert (pattern.exec (' http://www.codebit.cn ')); http://www.codebit.cn,www.codebit.cn
Pattern.lastindex = 0;
Alert (pattern.exec (' http://YITU.org ')); http://YITU.org,YITU.org
</script>
Summarize:
In global mode, if you want to start retrieving a new string after a pattern match is completed in a string, you must manually reset the Lastindex property to 0.