The common function method and simple application of JS regular expression

Source: Internet
Author: User
Tags array object end expression string split version variable


The regular expression is the focus and difficulty of the front-end learning. I am in a previous article to carry again JS the regular expression, to lead us to warm up the regular expression. This article mainly leads us to apply some regular expressions, and briefly introduce some common methods and objects in regular expressions, such as test, exec, match, replace, search, etc.
methods of regular Expression objects1, test, returns a Boolean value that indicates whether the pattern exists in the string being searched. Returns true if present, otherwise returns false. 2. Exec, run the lookup in a string with the regular expression pattern and return an array that contains the result of the lookup. 3, compile, the regular expression is compiled into the internal format, thus executing faster. the properties of the regular Expression object1, source, returns a copy of the text of the regular expression pattern. Read-only. 2, Lastindex, returns the character position, which is the starting position of the next successful match of the lookup string. 3, input ($_), returns the execution specification expression lookup string. Read-only. 4, Lastmatch ($&), returns the last matching character in any regular expression search. Read-only. 5, Lastparen ($+), if any, returns the last child match in any regular expression lookup. Read-only. 6, Leftcontext ($ '), returns the character in the lookup string between the position from the beginning of the string to the last match. Read-only. 7, Rightcontext ($ '), returns the character from the last match position to the end of the string in the searched string. Read-only. string objects Some methods related to regular expressions1, match, find the matching of one or more regular expressions. 2, replace, and replaces the substring that matches the regular expression. 3, search, retrieves the value that matches the regular expression. 4, split, the string into a string array. Case 1 Test method testing  //test method, test string, return True when conforming to mode, otherwise return false   var re =/he/;//simplest regular expression that will match the He word   var str = "he";  Conso Le.log (Re.test (str));//true   str = "we";   Console.log (Re.test (str));//false   str = "he";   Console.log (Re.test (str));//false, uppercase, if you want to match the case, you can specify the I flag (I is the representation of ignorecase or case-insensitive)   RE =/he/i;   Console.log (Re.test (str));//true   str = "certainly! He loves her! ";   Console.log (Re.test (str));//true, as long as he is included, if he or he is the only one and cannot have other characters, you can use ^ and $   RE =/^he/i;//de-character (^) Represents the character start position   Console.log (re.test (str));//false, because he was not at the beginning of str   str = "He is a good boy!";   Console.log (Re.test (str));//true,he is the character start position, and you need to use the $   RE =/^he$/i;//$ to represent the character end position   Console.log (Re.test ( STR));//false   str = "he";   Console.log (Re.test (str));//true  //Of course, this does not see how powerful the regular expression is, because we can use either = = or indexof   RE =/\s/;//\ In the above example. s matches any white space characters, including spaces, tabs, page breaks, and so on   str= "user name";//username contains spaces   Console.log (Re.test (str));//true  str = "User     name";//user name contains tabs   console.log (re.test (str));//true   re=/^[a-z]/i;//[] matches any character within a specified range , this will match the English alphabet, case-insensitive   str= "variableName";//variable names must begin with a letter   Console.log (Re.test (str));//true   str= "123ABC" ;   Console.log (Re.test (str));//false     Case 2 exec Test   var haoversion = "Haorooms 8";//8 means the system major version number   var re =/^[a-z]+\s+\d+$/i; The + number indicates that the character must appear at least 1 times, \s represents a white space character, \d represents a number   Console.log (Re.test (haoversion));//true, but we would like to know the major version number  //another method exec, Returns an array with the first element of the array as the complete match   re=/^[a-z]+\s+\d+$/i;   arr = re.exec (haoversion);   Console.log (arr[0]);//Will haoversion the full output, because the entire string matches exactly the re  //I just need to remove the number   re=/\d+/;   var arr = re.exec (haoversion);   Console.log (arr[0]);//8    //exec Returns an array of the 1th to n elements that contain any one of the child matches that appears in the match   re=/^[a-z]+\s+ (\d+) $/i;//with () To create a child matching   arr =re.exec (haoversion);   Console.log (arr[0])//whole haoversion, that is, the full match of regular expressions   Console.log (arr[1]);//8, the first child matches, the fact can also take out the major version number   Console.log (arr.length);//2   haoversion = "Haorooms 8.10"//Remove major and minor version number   RE =/^[a-z]+\s+ (\d+) \. (\d+) $/i;//. is one of the regular expression metacharacters, to use its literal meaning to escape the   arr = re.exec (haoversion);   Console.log (arr[0])//complete haoversion   Console.log (arr[1);//8   Console.log (arr[2));//10
Case 3 String Object some methods related to regular expressions   1, about replace, my previous blog was written specifically. You can also pass parameters. Please see: HTTP://WWW.HAOROOMS.COM/POST/JS_REPLACE_BL   2, other operations  //replace methods, used to replace the string   var str = "some money";   Console.log (Str.replace ("some", "much"); the first parameter of//much money  //replace can be regular expression   var re =/\s/;//whitespace character & nbsp Console.log (Str.replace (Re, "%"));//some%money  //The regular expression is extremely convenient when you do not know how many whitespace characters are in the string   str = "Some some             \tsome\t\f ";   RE =/\s+/;   Console.log (Re, "#") (str.replace); This will only replace the first occurrence of a heap of whitespace characters  //Because a regular expression can only be matched once, \s+ the first space and then exits   Re =/\s+/g;//g, global flag that will cause the regular expression to match the entire string   Console.log (Str.replace (Re, "@");//some@some@some@  // Another similarity is split   var str = "A-bd-c";   var arr = str.split ("-");/return ["A", "BD", "C"]  //If STR is user input, he may enter a-bd-c or enter a BD C or A_bd_c, but not ABDC ( That means he lost the wrong)   str = "a_db-c";//the user adds the separator s   re=/[^a-z]/i;//in his preferred way before we say ^ the character begins, but in [] it represents a negative character set  // Matches any character that is not in the specified range, which matches all characters except the letter   arr = Str.split (re);//Still return ["a", "BD", "C"];  //Find in string we use IndexOf, and the method corresponding to regular lookup is search   str = "My age is 18.Golden age!"; /age is not a certain, we can not find its location with indexof   RE =/\d+/;   Console.log ( (re); returns the found string to begin subscript  /note, because the lookup itself appears to return immediately after the first time, so there is no need to use G sign  // The following code is not wrong, but the G flag is redundant   re=/\d+/g;   Console.log ( (re));//still 10    var str = "My name is CJ." Hello everyone! ";   var re =/[a-z]/;//match all uppercase letters   var arr = Str.match (re);//return array   Console.log (arr);//The array will contain only one m, because we are not using the global horse With   re =/[a-z]/g;   arr = Str.match (re);   Console.log (arr);//m,c,j,h  //extract Word from string   re =/\b[a-z]*\b/gi;//\b denotes word boundary   str = "One Two Three R ";   Console.log (Str.match (re));//one,two,three,four    Case 4 RegExp Some properties of an object instancevar re =/[a-z]/i;   Console.log (Re.source)//will be a [a-z] string output//Note that direct Console.log (re) will be the regular expression along with the forward slash and flag output, which is the Re.tostring method definition of var re =/[a-z]/;   After the Exec method was executed, the lastindex attribute of re was modified, var str = "Hello,world!!!";   var arr = re.exec (str);   Console.log (Re.lastindex);//0, because no global flag is set the RE =/[a-z]/g;   arr = re.exec (str);   Console.log (Re.lastindex);//1 arr = re.exec (str);   Console.log (Re.lastindex);//7 var re =/[a-z]/;   var str = "Hello,world!!!";   Re.lastindex = 120;   var arr = re.exec (str); Console.log (re.lastindex);//0 Case 5 Static properties of RegExp objects  //input the last string to match (the string passed to the Test,exec method)   var re =/[a-z]/;   var str = "Hello,world!!!";   var arr = re.exec (str);   Console.log (regexp.input);//hello,world!!!   Re.exec ("TempStr");   Console.log (Regexp.input)//is still hello,world!!!, because TempStr mismatch  //lastmatch the last matching character   re =/[a-z]/g;   str = "HI";   Re.test (str);   Console.log (Regexp.lastmatch);//h   Re.test (str);   Console.log (regexp["$&"]);//i  ,$& is a short name for Lastmatch, but because it is not a valid variable name, you should ...  //lastparen last matched group   RE =/[a-z] (\d+)/gi;   str = "Class1 Class2 Class3";   Re.test (str);   Console.log (Regexp.lastparen);//1   Re.test (str);   Console.log (regexp["$+"])//2  //leftcontext   Returns the character  ///between the position found from the beginning of the string to the last match in the searched string Rigthcontext returns the character   re =/[a-z]/g from the last match position to the end of the string in the searched string;   str = "123abc456";   Re.test (str);   Console.log (regexp.leftcontext);//123   Console.log (Regexp.rightcontext);//bc456   Re.test (str);   Console.log (regexp["$"]);//123a   Console.log (regexp["$ '"]);//c456     Case 6 using the RegExp constructor to note pointsvar str = "\?";   Console.log (str);//Only output?   var re =/\?/;//will match? Console.log (Re.test (str));//true re = new RegExp ("\?"); /error, because inside of the string \ is the escape character \?  Want to get \? Re = new RegExp ("\");   /correct, will match? Console.log (Re.test (str));//true using special characters in regular expressionsASCII to represent special characters in hexadecimal numbers var re =/^\x43\x4a$/;//will match CJ Console.log (re.test ("CJ"),//true//can also use octal method re =/^\103\112 $/;//will match CJ Console.log (re.test ("CJ"));//true//can also use Unicode encoding re =/^\u0043\u004a$/;//use Unicode, you must start with U, then four-bit 1 of character encoding 6 in the form of Console.log (Re.test ("CJ"));

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: 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.