Home >Web Front-end >JS Tutorial >Summary of usage of match function in javascript_javascript skills
The match function in JavaScript uses regular expressions to search for strings and returns the search results as an array. It is very useful in actual development. The usage method is as follows:
stringObj.match( rgExp)
where stringObj is required. The String object or string literal to search for.
rgExp is required. Is a regular expression object containing the regular expression pattern and available flags. Can also be a variable name or string literal containing a regular expression pattern and available flags.
If the match function method in JavaScript does not find a match, return null. If a match is found an array is returned and the properties of the global RegExp object are updated to reflect the match. The array returned by the match function method in JavaScript has three attributes: input, index and lastIndex. The Input property contains the entire searched string. The Index property contains the position of the matching substring within the entire string being searched for. The LastIndex property contains the position next to the last character in the last match. If the global flag (g) is not set, element 0 of the array contains the entire match, and elements 1 to n contain any submatches that occurred in the match. This is equivalent to the exec method without setting the global flag. If the global flag is set, elements 0 to n contain all matches.
The following example demonstrates the usage of the match function method in js:
function MatchDemo(){
var r, re; // Declare variables.
var s = "The rain in Spain falls mainly in the plain";
re = /ain/i; // Create a regular expression pattern.
r = s.match(re); // Attempt to match the search string.
return(r); // Return to the first occurrence of "ain".
}
This example illustrates the usage of the match function method in js with g flag setting
function MatchDemo(){
var r, re; // Declare variables.
var s = "The rain in Spain falls mainly in the plain";
re = /ain/ig; // Create a regular expression pattern.
r = s.match(re); // Try to match the search string.
return(r); // The returned array contains all four occurrences of "ain"
//
}
The following lines of code demonstrate the use of the match function method in js for string literals.
var r, re = "Spain";
r = "The rain in Spain".replace(re, "Canada");
The match() method is used to find a specified value from a string. This method is similar to indexOf() and lastindexOf(). The difference is that it returns the specified value instead of the specified value in the string. Location. The indexOf() and lastindexOf() methods return the position number and return -1 if not found. Note that it is case sensitive