JavaScript Series article: detailed Jiu Zheng one of the expressions

Source: Internet
Author: User
Tags modifiers

Regular expressions are an ingenious tool that is often used to find and replace strings, JavaScript references Perl, and regular expression-related modules, which are very useful in development, and in some class libraries or frameworks, such as jquery, there are a lot of regular expressions, Therefore, to learn the regular expression is a basic requirement to improve the development skills. So today the blogger will come to a detailed summary of the regular expression of the relevant knowledge, hope that unfamiliar classmates, can also master the principle of regular expression and application.

In JS, there are two ways to create a regular expression, one is the literal way, and the other is the constructor, as follows:

var regex =/\w+/; // or var New REGEXP (' \\w+ ');

It may be noted that the use of the literal is much more concise than the constructor, \w represents a word, matches a single letter, number, or underscore, while using the RegExp constructor, our regular becomes "\\w" because we want to represent a backslash in the string \ We need to escape it. That is, add an escape character to the front. I believe we all know that in the literal regular expression of a match backslash \ 's regular, just write \ \ So, but in the string to express this regular, it is "\\\\" this way, this is because the first two of the string represents a backslash \, the latter two also represents a backslash \, and finally at the regular level, The result is still \ \.

For both of these forms of creation, you can add some suffix modifiers, which can be used either individually or together:

// Global Search // Ignore case // multi-line // Unicode // sticky/\w+/gi; New REGEXP (' \\w+ ', ' gi ');

From the English note, I believe everyone is probably knows, you need to pay attention to the U and y modifiers, they are ES6 new features, u means enable Unicode mode, for matching Chinese is particularly useful, and y is sticky, which means "adhesion", and g very similar, all belong to the global match, But they are also different, this we will introduce later.

The regular correlation method

With a regular expression object, how do you use it? JS in the regular and string in the prototype to provide a corresponding method, first look at the regular prototype of the two methods:

RegExp.prototype.test (str); RegExp.prototype.exec (str);

Both the test () and the Exec () methods above need to pass in a string to search for and match the string, but the test () method returns TRUE or false to indicate whether the string and the regular match, and the Exec () method returns an array of matching results when matched. If they do not match, only a null value is returned, and here is a look at the difference:

// regexp#test () var regex =/hello/; var result = regex.test (' Hello World ');   // true // regexp#exec () var regex =/hello/; var result = regex.exec (' Hello World ');   // [' Hello ']

For the Exec () method, if the regular contains a capturing group, the match appears in the result array:

// (Llo) is a capturing group var regex =/he (llo)/; var result = regex.exec (' Hello World ');   // [' Hello ', ' Llo ']

In the development, the test () method is generally used for user input validation, such as mailbox verification, mobile phone number verification, and the exec () method is generally used to obtain valuable information from a specific content, such as from the user's mailbox input to get its ID and mailbox type, from the mobile phone number to obtain the attribution of the number and so on.

String-related methods

These are the two methods in the regular prototype, and now look at what methods are available in the string prototype:

String.prototype.search (RegExp); String.prototype.match (RegExp); String.prototype.split ([separator[, limit]]); String.prototype.replace (Regexp|substr, newsubstr|function);

First, the String#search () method, which matches the string based on a regular parameter, returns the index at the first match if the match succeeds, or 1 if the match fails.

// string#search ()' Hello World ' search (/hello/);    // 0' Hello World ' search (/hi/);       // -1

The String#match () method, similar to the Regexp#exec () method, returns an array of results, except that if the regular parameter of String#match () contains the global tag g, only matching substrings appear in the result, and the capturing group is ignored, as with RegExp There is some discrepancy #exec (). And look at the following code:

// string#match ()' Hello Hello '. Match (/he (Llo)/);     // [' Hello ', ' Llo '] // String#match () discards the capturing group ' Hello hello ' when it encounters the global G modifier . Match (/he (llo)/g);    // [' Hello ', ' hello '] // regexp#exec () still contains capturing group /he (Llo)/g.exec (' Hello hello ');     // [' Hello ', ' Llo ']

Therefore, if you need to always return a capturing group as a result, you should use the Regexp#exec () method instead of the String#match () method.

Let's talk about the String#split () method, which is used to split the string and then return an array result containing its substrings, where both the separator and the limit parameters are optional, separator can be specified as a string or a regular. Limit specifies the maximum limit for the number of results returned. If separator is omitted, the array result of the method contains only its own source string, and if Sparator specifies an empty string, the source string is split in characters, or if separator is a non-empty string or regular expression, The method splits the source string in units of this parameter. The following code demonstrates the use of this method:

//String#split ()' Hello '. split ();//["Hello"]' Hello '. Split (');//["H", "E", "L", "L", "O"]' Hello '. Split (', 3);//["H", "E", "L"]//specify a non-empty stringvarSource = ' Hello World ';varresult = Source.split (");//["Hello", "World"]//or use regular expressionsvarresult = Source.split (/\s/);//["Hello", "World"]

If Separtor is a regular expression and the capture group is included in the regular, the capturing group also appears in the result array:

// String#split () regular capture group var source = ' Matchandsplit '; var result = Source.split (' and ');     // ["Match", "split"] var result = Source.split (/and/);     // ["Match", "split"] // Regular with capturing group var result = Source.split (/(and)/);   // ["Match", "and", "split"]

Finally, introduce the String#replace () method, which performs both the find and replace of two operations.

From the function signature above, the method accepts two parameters: the first argument can be a regular expression or a string, they all represent the substring that will be matched, the second argument can specify a string or a function, if you specify a string, Indicates that the string will replace the substring that has been matched, and if a function is specified, the return value of the function replaces the matched substring.

The String#replace () method eventually returns a new, replaced string. The following shows the use of the Replace method, respectively:

 //  String#replace ()  var  Source = ' matchandsplitandreplace ' ;   var  result = Source.replace (' and ', '-'); //  "Match-splitandreplace"  //  var  result = Source.replace (/and/, function   () { return  '-' 

As you can see from the code above, ' and ' is replaced with '-', but we also notice that only the first ' and ' is replaced, and the back is not processed. Here we need to understand that the String#replace () method replaces only the first occurrence of the matching string, and if we need to replace it globally, we need to specify the first parameter as a regular expression and append the global G modifier as follows:

// string#replace () global substitution var source = ' matchandsplitandreplace '; var // "Match-split-replace" var function () {  return '-';});                                        // "Match-split-replace"

Beginners to see the above code, may feel puzzled, for the second parameter, directly specify a string is also quite simple, why we use a function and then return a value. Let's look at the following example to find out:

// string#replace () Replace the argument list of a function var source = ' matchandsplitandreplace '; var function (Match, p1, P2, offset, string) {    console.group (' match: ');  Console.log (Match, p1, P2, offset, string);  Console.groupend ();   return '-';});                                        // "Match-split-replace"

In the above code, the first parameter is a regular expression, which contains two capturing groups (and) and (ND), and the second parameter specifies an anonymous function with some parameters in its list of functions: Match, p1, P2, offset, string, corresponding to the substring to match to, the first capturing group, The second capturing group, the index of the matched substring in the source string, the source string, we can call this anonymous function as "Replacer" or "Replace function", in the replacement function's argument list, match, offset and string are always present at each match, while the middle P1, P2 and other capturing groups, the String#replace () method will be populated according to the actual matching situation, and of course, we can also obtain these parameter values according to arguments.

The following is the result of the console printing after the code is run:

Now, specifying a function is much more powerful than specifying a string, and each match gets that useful information, we can do some manipulation of it, and finally return a value as a new substring to replace. Therefore, it is recommended to use this method when calling the String#replace () method.

The above is a common method of the String class related to regular, it should be noted that the String#search () and String#match () method signature parameters are regular objects, if we pass other types of parameters, will be implicitly converted to regular objects, The specific step is to first call the ToString () method of the parameter value to get the value of the string type, and then call New RegExp (Val) to get the regular object:

//String#search (New RegExp (Val.tostring ()))' 123 123 '. Search (1);//0' True false '. Search (true);//0' 123 123 '. Search (' \\s ');//3varo ={toString:function() {    return' \\s '; }};' 123 123 '. Search (o);//3//String#match (New RegExp (Val.tostring ()))' 123 123 '. Match (1);//["1"]' True false '. Match (true);//["true"]' 123 123 '. Match (' \\s ');// [" "]varo ={toString:function() {    return' 1 (23) '; }};' 123 123 '. Match (O);//"123", " All"]

The split () and replace () methods do not convert the string to a regular expression object, and for other types of values, only their ToString () method is called to turn the parameter value to a string, and no further to the regular conversion, you can test it yourself.

The above is the relevant basic knowledge of the regular and common methods, confined to the reason, more about the regular expression of content, Bo Master will arrange in the next article introduced and explained, please look forward to.

Resources:

Https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

Https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String

Https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

http://es6.ruanyifeng.com/#docs/regex

JavaScript Series article: detailed Jiu Zheng one of the expressions

Related Article

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.