JS regular function match, exec, test, search, replace, split

Time:2021-1-16

Match method
The regular expression pattern is used to perform a lookup on a string, and the result containing the lookup is returned as an array.
stringObj.match(rgExp)
parameter
stringObj
Required. The string object or string text to look for.
rgExp
Required. Is a regular expression object that contains regular expression patterns and available flags. It can also be a variable name or string literal that contains regular expression patterns and available flags.
Other descriptions are the same as exec, except that if the expression of match matches the global tag g, all matches will appear instead of loops, but all matches will not contain sub matches.
Example 1:
Function matchdemo() {VaR, R, re; / / declare variables. Var s = the rain in space falls mainly in the plain; re = / (a) in / Ig; / / create a regular expression pattern. R = s.match (RE); / / try to match the search string. document.write (r) ; / / the returned array contains all four matches of “ain”, R [0], R [1], R [2], R [3]. //But there is no sub match a. }Output result: ain, ain, ain, ain
Exec method
Use regular expression pattern to search in the string and return the first value (array) of the search result. If the match fails, return null.
rgExp.exec(str)
parameter
rgExp
Required. A regular expression object that contains regular expression patterns and available flags.
str
Required. The string object or string text in which to perform the lookup.
The return array contains:
Input: the value of the whole searched string;
Index: the position (bit) of the matching result;
Lastinput: the position of the next matching result;
Arr: result value, arr [0] full match result, arr [1,2…] is the sub match of () in the expression, 1,2… From left to right.
Example 2:

Copy codeThe code is as follows:
function RegExpTest(){
var src=”http://sumsung753.blog.163.com/blog/I love you!”;
Var re = / – W + / g; / / note that G will match the full text, and if not, only the first match will be returned.
var arr;
while((arr = re.exec (SRC))! = null) {/ / exec makes arr return the first match, and a while loop will make re search for the next match under the action of G.
document.write(arr.index + “-” + arr.lastIndex + “:” + arr + “<br/>”);
for(key in arr){
document.write(key + “=>” + arr[key] + “<br/>”);
}
document.write(“<br/>”);
}
}
window.onload = RegExpTest();

Output results:
0-1: I / / 0 is the index, I is the location, and 1 is the next matching location
input=>I love you!
index=>0
lastIndex=>1
0=>I
2-6:love
input=>I love you!
index=>2
lastIndex=>6
0=>love
7-10:you
input=>I love you!
index=>7
lastIndex=>10
0=>you
Note: according to the manual, exec only returns the first value of the matching result. For example, in the above example, if you do not use the while loop, only ‘I’ will be returned (although the love and you after I space conform to the expression), regardless of whether the re expression uses the global tag g or not. However, if the global flag G is set for the regular expression, exec starts the search at the position indicated by the value of lastindex. If the global flag is not set, exec ignores the value of lastindex and searches from the beginning of the string. Using this feature, we can call exec repeatedly to traverse all matches, which is equivalent to match having g flag.
Of course, if regular expressions forget to use G and use loops (for example, while, for, etc.), exec will loop the first one every time, causing a dead loop.
The output of exec will contain child matches.
Example 3:

Copy codeThe code is as follows:
function execDemo(){
Var R, re; / / declare variables.
var s = “The rain in Spain falls mainly in the plain”;
re = /[\w]*(ai)n/ig;
r = re.exec(s);
document.write(r + “<br/>”);
for(key in r){
document.write(key + “-” + r[key] + “<br/>”);
}
}
window.onload = execDemo();

Output:
rain,ai
input-The rain in Spain falls mainly in the plain
index-4
lastIndex-8
0-rain
1-ai
Test method
Returns a Boolean value indicating whether the given regular expression is matched in the searched string.
rgexp.test(str)
parameter
rgexp
Required. A regular expression object that contains regular expression patterns or available flags.
str
Required. The string on which to test the lookup.
explain
The test method checks whether the string matches the given regular expression pattern. If so, it returns true, otherwise, it returns false.
Example 4:

Copy codeThe code is as follows:
function TestDemo(re, s){
var s1;
if (re.test(s))
S1 = match regular form;
else
S1 = does not match the regular form;
return(“‘” + s + “‘” + s1 + “‘”+ re.source + “‘”);
}
window.onload = document.write(TestDemo(/ab/,’cdef’));

Output result: ‘cdef’ does not match the regular expression ‘ab’
Note: Test () inherits the lastindex attribute of regular expression, which should be paid attention to when the expression matches the global flag G.
Example 5:

Copy codeThe code is as follows:
function testDemo(){
Var R, re; / / declare variables.
var s = “I”;
Re = / I / Ig; / / creates a regular expression pattern.
document.write ( re.test (s) + “< br / >”); / / returns the boolean result.
document.write(re.test(s) + “<br/>”);
document.write(re.test(s));
}
testDemo();

Output results:
true
false
true
When test() is called for the second time, lastindex points to the location 1 of the next match, so the second match is unsuccessful, and lastindex points to 0 again, which is equal to the third match. The following example shows the lastindex property of test:
Example 6:

Copy codeThe code is as follows:
function testDemo(){
Var R, re; / / declare variables.
var s = “I”;
Re = / I / Ig; / / creates a regular expression pattern.
document.write ( re.test (s) + “< br / >”); / / returns the boolean result.
document.write ( re.lastIndex ); / / returns the boolean result.
}
testDemo();

Output:
true
1
Solution: point the lastindex property of test () to 0 again each time, re.lastIndex = 0;

Search method
Returns the position (partial shift) of the first substring that matches the regular expression lookup.
stringObj.search(rgExp)
parameter
stringObj
Required. The string object or string text on which to look up.
rgExp
Required. A regular expression object that contains regular expression patterns and available flags.
Note: if it is found, the offset from the sub character to the beginning is returned, otherwise – 1 is returned.
Example 6:

Copy codeThe code is as follows:
function SearchDemo(){
Var R, re; / / declare variables.
var s = “The rain in Spain falls mainly in the plain.”;
Re = / falls / I; / / creates a regular expression pattern.
re2 = /tom/i;
R = s.search (RE); / / find the string.
r2 = s.search(re2);
Return (“R:” + R + “; R2:” + R2); / / returns the boolean result.
}
document.write(SearchDemo());

Output: R: 18; R2: – 1
Replace method
Returns the copy of a string after text replacement according to a regular expression.
stringObj.replace(rgExp, replaceText)
parameter
stringObj
Required. The string object or string text to perform the replacement. The string is not modified by the replace method.
rgExp
Required. Is a regular expression object that contains regular expression patterns or available flags. It can also be a string object or text. If rgexp is not a regular expression object, it will be converted to a string and a precise lookup will be made; do not try to convert the string to a regular expression.
replaceText
Required. Is a string object or string text. For each position in the matching rgexp in stringobj, replace it with the text contained in the object. In JScript 5.5 or later, the replacetext parameter can also be a function that returns replacement text.
explain
The result of the replace method is a copy of the stringobj object that completes the specified replacement. It means to replace the matching items, and other unchanged items are returned as the original of stringobj.
ECMAScript V3 specifies that the parameter replacement of the replace() method can be a function rather than a string. In this case, the function is called for each match, and the string it returns is used as replacement text. The first argument to this function is the string that matches the pattern. The next parameter is the string that matches the subexpression in the pattern, which can have 0 or more of these parameters. The next parameter is an integer that declares where the match occurs in the stringobject. The last parameter is the stringobject itself. The result is to replace each matching substring with the string value of the corresponding return value of the function call. Function as a parameter can be more complex operation.
Example 7:

Copy codeThe code is as follows:
function f2c(s) {
Var test = / (- D + (\. [D *)?) f / B / g; / / indicates that the possible modes of Fahrenheit temperature are: 123f or 123.4f. Note that the G pattern is used here
return(s.replace
(test,
function(Regstr,$1,$2,$3,newstrObj) {
Return ((“< br / >” + regstr + “< br / >” + ($1-32) * 1 / 2) + “C” + “< br / >” + / / replace the following two lines
$2 +”<br/>” + $3 +”<br/>” + newstrObj +”<br/>” );
}
)
);
}
document.write(f2c(“Water: 32.2F and Oil: 20.30F.”));

Output results:
Water: / / for characters that do not match the regular character, output as the original character
32.2f / / the original string regstr of the first string that matches the regular
0.100000000000142c / / the replacement result of the first sub pattern matching of the first string matched with the regular string is $1
. 2 / / the replacement result of the second sub pattern match of the first string that matches the regular string, here we do not replace it with $2
7 / / offset of $3 for the first sub match of the first string that matches the regular
Water: 32.2f and oil: 20.30f. / / original string newstrobj
And oil: / / characters that do not match the regular
20.30f / / the original string of the second string that matches the regular string
-5.85c / / the first sub pattern of the second string matching the regular string and the matching replacement result
. 30 / / the replacement result of the second sub pattern match of the second string matched with the regular string, we do not replace it here
22 / / the offset of the first sub match of the second string that matches the regular string
Water: 32.2f and oil: 20.30f. / / original string
. / / characters that do not match the regular
We use all the above function parameters. In practice, we only need to replace xxf with xxC. According to the requirements, we do not need to write so many parameters.
Example 8:

Copy codeThe code is as follows:
function f2c(s) {
Var test = / (- D + (\. [D *)?) f / B / g; / / indicates that the possible modes of Fahrenheit temperature are: 123f or 123.4f
return(s.replace
(test,
function(strObj,$1) {
return((($1-32) * 1/2) + “C”);
}
)
);
}
document.write(f2c(“Water: 32.2F and Oil: 20.30F.”));

Output: water: 0.100000000000142c and oil: – 5.85c
More applications:
Example 9:

Copy codeThe code is as follows:
function f2c(s) {
var test = /([\d]{4})-([\d]{1,2})-([\d]{1,2})/;
return(s.replace
(test,
function($0,$1,$2,$3) {
return($2 +”/” + $1);
}
)
);
}
document.write(f2c(“today: 2011-03-29”));

Output: Today: 03 / 2011
Split method
Splits a string into substrings and returns the result as an array of strings.
stringObj.split([separator[, limit]])
parameter
stringObj
Required. The string object or text to be decomposed. The object is not modified by the split method.
separator
Optional. A string or regular expression object that identifies whether one or more characters are used to separate strings. If this option is ignored, a single element array containing the entire string is returned.
limit
Optional. This value is used to limit the number of elements in the returned array.
explain
The result of the split method is an array of strings, which is decomposed at each separator position in tingobj. The separator is not returned as part of any array element.
Example 10:

Copy codeThe code is as follows:
function SplitDemo(){
var s, ss;
var s = “The rain in Spain falls mainly in the plain.”;
//Regular expressions, separated by s, regardless of size.
ss = s.split(/s/i);
return(ss);
}
document.write(SplitDemo());

Output: the rain in, pay fall, mainly in the plain

The exec () method, match () method and search () method of JS regular expression

First look at the code:

var sToMatch = “test, Tes, tst, tset, Test, Tesyt, sTes”;
var reEs = /es/gi;
alert(reEs.exec(sToMatch));
alert(sToMatch.match(reEs));
alert(sToMatch.search(reEs));

The contents of the three pop-up boxes are as follows:

JS regular function match, exec, test, search, replace, split

JS regular function match, exec, test, search, replace, split

JS regular function match, exec, test, search, replace, split

The results are as follows

1. The exec () method of regexp has a string parameter and returns an array. The first entry of the array is the first match; the others are back references. So the first result returned is the first matching value es (case insensitive).

2. The string object has a match () method that returns all the matching data contained in the string. This method calls the string object and passes it a regexp object. So the second pop-up statement returns all arrays that match the regular expression.

3. The string method of search () is similar to indexof (), but it uses a regexp object instead of just a substring. The search() method returns the location of the first matching value. So the third pop-up is “1”, that is, the second character matches. Note that the search () method does not support global matching of normal expressions (with parameter g).