String method for pattern matching:
String supports 4 ways to use regular expressions:
Seach () is used to retrieve the parameter is a regular expression, returns the position of the first substring to match, returns-1 if the argument is not a regular expression, first converts it to a regular expression through the Rexexp constructor, and the Seach () method does not support global search. it ignores modifier g;
Replace () is used to retrieve and replace operations, the first argument is a regular expression, and the second is the string to be replaced. It retrieves the string that invokes the method, replaces the pattern-matching substring with the second argument, and matches the full text if the modifier g is included. If the first argument is not a regular expression but a string, the direct search replaces the string;
Text.replace (/javascript/gi, ' javascript ') means searching for case-insensitive JavaScript in text full-text to replace JavaScript
if ($ plus digits) appear in the string used for substitution, the replace () method is replaced with text that matches the subexpression of the $ plus number reference, such as:
var quote =/"([^"]*) "/g
Text.replace (Quote, ' "$"); Full-Text Search and/"([^"]*) "/matching string, replace with" $ "(means to change only the double quotation marks on both sides to the Chinese half, while the content stored in is unchanged) stores a string that matches the subexpression in the first left parenthesis;
The only argument to match () is a regular expression that returns an array of matching results, and if the argument is not a regular expression, it is first converted to a regular expression by the Rexexp constructor;
(b) If the regular expression with modifier g,match () returns an array element that matches all the strings obtained;
(b) If the regular expression does not have a modifier g,match () retrieves only the first match, but he also returns an array (the first element of the array is the entire string that matches, and the next element is the string in the expression that matches all the parentheses around the subexpression, each element corresponding to a bracket)
Such as:
var url =/(\w*): \/\/([\w.] +) \/(\s*)/;
var text = ' Http://www.w3school.com.cn/jsref ';
var result = Text.match (URL);
if (result!= null) {
var fullurl = result[0];
var protocol =result[1];
var host = result[2];
var path = result[3];
}
Split () splits the string by the delimiter specified by the parameter into an array of multiple substrings, such as:
' 123,345,789 '. Split (', '); return [' 123 ', ' 345 ', ' 789 ']
' 1, 2, 3, 4, 5, 6 '. Split (/\s*,\s*/); return [' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ']
The above is a small series for everyone to bring the JavaScript learning notes for the pattern matching the whole content of the string method, I hope to help you, a lot of support cloud Habitat Community ~