The JS method associated with the regular is combined with its application in the project

Source: Internet
Author: User

A preface to the application of JS method in the project

There are more regular matches in recent projects, so it is intended to thoroughly understand and summarize the methods that are relevant to the regular, and then combine the situations used in the project. There are 7 JS methods related to the regular, namely the RegExp object's compile (), exec (), test () and the string () method that supports the regular expression is search (), match (), replace (), split ().

RegExp object Method Compile () method

This method is used to change and recompile regular expressions.  Syntax: Regexpobject.compile (regexp, modifier); Parameter 1 is a regular expression, and parameter 2 is the type that specifies the match. "G" is used for global matching, "I" is used for case sensitivity, and "GI" is used for global case-sensitive matching.

1 varstr = ' Hello World Hello World ';2 varPatt =/hello/G;3 //Replace "Hello" with "HI" string globally4 varstr2 = str.replace (Patt, ' Hi '));5 Console.log (str2);6Patt =/world/G;7 Patt.compile (Patt);8 //Replace " World" with "all the World" string globally9str2 = str.replace (Patt, ' all the world ');TenConsole.log (STR2);

In the console input as shown in figure:

EXEC () method

This method is used to retrieve the matching of regular expressions in a string. Syntax: Regexpobject.exec (String). parameter is the string to retrieve. Return value: Returns an array that holds the matching results and returns null if no match is found.

1 varStr= "Visit W3school, W3school is a place to study web technology."; 2 varPATT1 =NewREGEXP ("W3school", "G");3 varPATT2 =NewREGEXP ("W3school");4 varresult;5  while(Result = Patt1.exec (str))! =NULL)  {6 Console.log (result);7 Console.log (patt1.lastindex);8  }9  //returns null after jumping out of the loop, and resets the lastindex value to 0Ten Console.log (patt1.lastindex); One  A Console.log (patt2.exec (str)); - Console.log (patt2.lastindex); - /* the While (result = patt2.exec (str)) = = null) { - Console.log (result); - Console.log (patt2.lastindex); -  } + Note: This loop is a dead loop, and a non-global match only matches the first match to the value Patt2.exec (str)) to return an array.  - */

Figure (1) figure (2)

    

In addition to the array element and the length property, the Exec () method returns two properties. The Index property declares the position of the first character of the matched text. The input property holds the string that was retrieved. we can see that when calling the Exec () method of a non-global REGEXP object (such as a variable patt2, figure (2)), the returned array is the same as the array returned by the calling Method String.match (), and the LastIndex default is 0.

However, when Regexpobject is a global regular expression (such as variable patt1, figure (1)), the behavior of exec () is slightly more complex. It will begin retrieving string strings at the character specified by the LastIndex property of Regexpobject. When exec () finds text that matches the expression, it sets the Regexpobject LastIndex property to the next position of the last character of the matched text after the match. This means that you can iterate through all the matching text in a string by calling the Exec () method repeatedly. When exec () can no longer find a matching text, it returns null and resets the LastIndex property to 0. With the figure (1), we see that the index value is 6 when the first retrieval of ' W3cschool ', and Lastindex becomes 14, then the string is retrieved from Lastindex, the second retrieved ' W3cschool ', and Lastindex becomes 24. Finally exit the loop, lastindex resets to 0.

Test () method

This method is used to detect whether a string matches a pattern. Syntax: Regexpobject.test (string); return value: Returns True if the string contains text that matches regexpobject, otherwise false. The following applies the regular application used in the project, mobile phone number verification:

1 varReg =/(13\d|14[57]|15[^4,\d]|17[678]|18\d) \d{8}|170[059]\d{7}/;2 //Logon events3$ (". Lonbtn"). Click (function() {4     varnum = $ ("#phoneNum"). Val ();5     varCode = $ ("#code"). Val ();6     if(!reg.test (num) | | code = = " ) {7Mui.alert ("Phone number or CAPTCHA error"));8}Else {9Window.location.href = "Memabout.html";Ten     } One})

Match image format Regular:

//Upload image functionfunctionuploadimg (Domele) {$ (Domele). Change (function() {        if(typeofFileReader = = = ' undefined ') {alert ("Your browser does not support FileReader"); return; }        varFile = This. files[0];  Console.log (file); //Picture Format Regular        if( !/(.*). (JPG|BMP|GIF|ICO|PCX|JPEG|TIF|PNG|RAW|TGA) $/. Test (File.name)) {Alert ("Please upload picture format content"); return; }//if (file.size/1024 > 5) {//file.size picture size unit is B, convert to KB. //alert ("Upload image size should not exceed 5KB");//return;//        }        varR =NewFileReader ();        R.readasdataurl (file); R.onload=function(e) {//Console.log (this.result);$ (Domele). Next (). HTML ('  This. Result + ' "alt=" Picture ">"); }                        })}

  

String Object method Search () method

This method is used to retrieve a substring specified in a string or to retrieve a substring that matches a regular expression. Syntax: Stringobejct.search (regexp), return value: The start position of the first substring that matches the regexp. No returns are found-1. Pay special attention to the search () method does not perform a global match.

var str4 = "Hello3 w4orld"; // retrieves the specified substring console.log (Str4.search (/wor/));   // -1 // retrieves a substring that matches a regular expression non-global Console.log (Str4.search (/\d/));  // 5 // Global Match Console.log (Str4.search (/\d/g));   // 5

The same as the return value in both global and non-global matches, the description does not perform a global match.

Match () method

The method can retrieve the specified value within a string, or find a match for one or more regular expressions. Syntax: Stringobject.match (Searchvalue) or Stringobject (regexp). Return value: The array that holds the matching result. The contents of the array depend on whether RegExp has global identity G.

var str= "Visit W3school, W3school is a place to study web technology." ;  Console.log (Str.match (' W3school '));   // The parameter is the RegExp object global Search console.log (str.match (/\d+/g)); // parameter is a RegExp object non-Global search performs only  one match Console.log (Str.match (/\d+/));

Figure (3)

When invoking the Metch () method of a String object, the parameter is non-global, and the returned array is the same as the array returned by the calling Method Regexp.exec (). However, the contents of the array returned by the global match are very different from the former, and its array elements hold all the matching substrings in the stringobject, and there is no index attribute or input property. (3)

Get Request parameter Address:

/** * GET request Address parameter * @param String name*/functionGeturlparam (name) {varReg =NewRegExp ("(^|&)" + name + "= ([^&]*) (&|$)");//constructs a regular expression object that contains a target parameter    //the regular is looking for the &+url parameter name = value +&Console.log (REG);///(^|&) index= ([^&]*) (&|$)/    varSearch =encodeURI (Window.location.search);   Console.log (search); //? index=1    varr = Search.substr (1). Match (REG);//Match target ParametersConsole.log (R);//["Index=1", "", "1", "", index:0, Input: "Index=1"]    if(r! =NULL)returndecodeURI (unescape (r[2));return NULL;//Return parameter Values};varGindex = Geturlparam ("index");
Replace () method

This method is used to replace other characters with some characters in a string, or to replace a substring that matches a regular expression. Syntax: Stringobject.repalce (REGEXP/SUBSTR, replacement); Return value: A new string. Note: If RegExp has global identity G, then the Replace () method replaces all matching substrings. Otherwise, it replaces only the first matched substring.

Split () method

This method is used to split a string into a string array.  Syntax: Stringobject.split (separator, howmany); The first argument: a string or a regular expression. The second parameter: optional, which specifies the maximum length of the returned array.

1 var str5 = "15hell1o w3o"; 2 console.log (Str5.split (/\d+/));  //   ["", "hell", "O W", "O"]3  // empty string ("") as a split, the string will be split between each character.  4  console.log (Str5.split (""));   //

  

The JS method associated with the regular is combined with its application in the project

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.