Regex has always been both loved and hated, because using regex allows you to solve complex problems quickly and easily. The most regex is string manipulation. Their relationship was a bit silly and complicated, and needed to be sorted out.

 

Common methods of re are:

1, test: pattern. Test (string); Returns true or false;

2, exec: pattern. Test (string); Returns an array of matches, null for none.

PS: Multiple calls to the same string always return the first match. The next match is returned until the end of the string only if the (g) global property is set.

Var pattern=/<(\w+) (>) /g; var se=pattern.exec(str); var se1=pattern.exec(str); The console. The log (se) / / / "< tt >", "tt", ">"] array is the first match, the second is for the first item to capture the console. The log (se1) / / / "< rr >", "rr", ">"] array is the first match, the second item represents the first capture, The third item represents the second capture itemCopy the code

 

We can use the re method in a string:

Match: takes only one argument, essentially the same as calling pattern.exec(), and returns the same array.

var str='<tt><rr><rr/><ll><lt></lt><ll/><dd></dd><rr/><tt><tt/><rr><rr/>';
    var ss=str.match(/<\w+>/);    //[ "<tt>" ]
    var sss=str.match(/<\w+>/g);    //[ "<tt>", "<rr>", "<ll>", "<lt>", "<dd>", "<tt>", "<rr>" ]
Copy the code

 

2. Search: takes only one argument and returns the index of the first match in the string. If no match is found, -1 is returned

Var sea = STR. Search (/ < > \ w + /); //0 var sea1=str.search(/<\w+\/>/); / / 8Copy the code

 

3, replace:

var text="cat bat ut dat"; var re=text.replace("at","11"); //c11 bat ut dat var re1=text.replace(/at/g,"11"); //c11 b11 ut d11 var re2=text.replace(/(.a(t))/g, "$1$2") ; //catt batt ut datt function replaceText(text){ return text.replace(/at/g,function(match,pos,originalText){ console.log(match+" "+pos+" "+originalText); })} replaceText(text); // At 1 cat bat ut dat //at 5 cat bat ut dat //at 12 cat bat ut dat // The final result is cundefined bundefined ut dundefined // Undefined because the function returns no valueCopy the code

 

Split: Can take a second argument indicating the length of the returned array

var result=text.split(/\s/); //[ "cat", "bat", "ut", "dat" ] var result1=text.split(/\s/,2); //[ "cat", "bat"]Copy the code