First, regular expressions in JavaScript
In JavaScript, you can construct regular expressions using RegExp objects. We need to create a new instantiated regexp () object that can pass in two parameters: the first parameter is a matching pattern, the second parameter is an option, and three parameters can be passed in. I means case-insensitive, and G represents a global match, that is, matches all of the qualifying strings, and m indicates that multiple matches are performed. Examples are as follows:
var reg = new RegExp ("Hello", "I"); Represents a hello string in a matching string and is not case-sensitive.
Second, using EXEC for pattern matching
There is a method in RegExp that can match the pattern and return the result: Exec (). This method is very important, basically is the use of JS for pattern matching required function. However, the return value of this function is not clear to many people, so it is often wrong when actually used. Here is a systematic introduction to some of the methods used by EXEC ().
The basic format of the Exec () is: Regexpobject.exec (String), where Regexpobject is the set regular matching object and string is the one to be matched. Returns an array if a successful match is returned, or null if there is no string part that matches successfully.
The focus here is on this array. What exactly is the array returned to? Take a look at the following experiment.
var re = new RegExp ("[? #&]" + user + "= ([^&#]*)", "I")
This code makes a URL match that can be used to get the argument part after user=, so what will the results return if you use a URL and use this mode for the exec operation? For example, we have the following
www.qq.com?user=Tom&psw=123456
The result of the array returned by exec is: [? user=tom, Tom]. You can see that the first element of the returned array is the string to which the entire matching pattern matches, and the second matches the character exactly as the parameter value. This is the exec match return
Rule: The first element is the entire matching string, and the string that matches the grouping defined by each () in the pattern is returned from the second argument. The face ([^&#]*) returns a string that does not start with & or #, which corresponds to the following
Parameters.
If we modify the defined pattern to [? #&] "+ (user) +" = ([^&#]*), then the array returned by exec () is [? user=tom, User, Tom].
Construct regular expression validation using the Exec () method in JS