Introduction to javascript Regular Expressions-javascript tips-js tutorial

Source: Internet
Author: User
Several applications related to regular expressions in javascript are described in detail in this article. If you need them, refer to the string object.
1. str. match (RegExp)
Search for strings matching RegExp in str and save them in a Number Group,
If RegExp is not set globally (/g), it only matches once.

The Code is as follows:


("Abc0000dwfwabcwef2abc3wfwabcas00000000abcqwf24j234h"). match (/abc \ d */g );
// Result
["Abc112", "abc", "abc3", "abc", "abc"]


In this method, if the regular expression is not in the global match mode (g tag), the first element will be the matching string, and the rest will be the strings captured in the regular expression, the array has two attributes:
Input string used for detection
The start position of the index-matched string in the detection string.
(For details about these two attributes, refer to the RegExp.exe c () method)
2. str. search (regExp)
Returns the position of the first string matching RegExp. If no match is returned,-1 is returned. The Global tag is meaningless because it only matches once,
This method also ignores the lastIndex attribute of regExp and always searches from the start of the string.
3. str. replace (RegExp, replaceText)
ReplaceText replaces the string matching RegExp with replaceText. If RegExp is not set globally, it only matches once. In Global mode, all matching strings are replaced.
If RegExp uses capture group match, $ in replaceText has a special meaning.
$1, $2,..., $99 // text that matches the 1st to 99th subexpressions in RegExp.
$ & // Substring that matches regexp.
$ '// The text on the left of the matched substring.
$ '// The text on the right of the matched substring.
$ // Match the $ symbol itself.
Note: you need to consider the number of captured groups in RegExp. If you set only two captures, $3 will not have any special meaning.
("123ab12c11d_4532"). replace (/a (B \ d *) c (\ d *) d/, "$1 @ $2 -")
// You will get:
"123b12 @ 11-_4532"
4. str. replace (RegExp, function)
The second parameter of str. replace can be a function. The return value of the function will be replaced by matching characters,
Note: If you want to globally match RegExp, you still need the global g tag.
The function parameters are as follows:
Matched string,
Capture substrings configured (multiple ),
Match the start position of the string,
Original string used for matching
Note: define the number of function parameters based on the number of capture groups in RegExp, if the parameter is too large, the "starting position of matching string" and "original string used for matching" cannot appear in the parameter. Of course, you can use the arguments object in the function to solve this problem, arguments (arguments. length-2) is the starting position of the matching string, arguments (arguments. length-1) is the original string used for matching.

The Code is as follows:


Var newStr = ("123ab12c11d_4532 "). replace (/a (B \ d *) c (\ d *) d/g, function (s, s1, s2, pos, oldStr ){
Return "@" + s1 + "@" + s2 + "@";
});
// You will get
"123 @ b12 @ 11 @ _ 4532"


5. str. split (RegExp [, limit])
Splits string 'str' into an array using a matching string. The limit parameter is optional and is used to limit the length of the returned array.
("Ada2afa4fcas6afa"). split (/\ d/, 3) // "ada, afa, fcas"
62.16regexp.exe c ("str") Method
Search for matched strings in str. Note that this method matches only once each time. To match multiple strings, set RegExp to/g and run the exec () method multiple times, return value for each matching result = RegExp.exe c ("str ")
Result is an array. The length of this array is 1, and the array elements are matched substrings,
In addition, this array is assigned with two additional attributes:
Result. index indicates the starting position of the matched substring in the original string.
Result. input is the original string.
If no matching substring can be found, return result = null and set RegExp. lastIndex = 0.
RegExp. lastIndex is the attribute of a regular expression. It indicates the position of the string to start matching. The initial value is 0.
If RegExp is set to global, use the same RegExp to match a new string once after it is matched. Set RegExp. lastIndex = 0 first.
If RegExp is not a global match mode, and a loop is written in the program, the result returned by the base determines whether to terminate the match and try to match the string, as long as there are substrings that meet the matching conditions, it will inevitably lead to an endless loop, because non-global match only matches the string once, and the result is that each matching operation matches the first substring, the returned result is not null, which is a relatively easy mistake.

The Code is as follows:


Var str = "1 Visit W3School, W3School is a place to study web technology .";
Var patt = new RegExp ("W3School", "g ");
Var result;
Document. write (patt. lastIndex +"
");
Document. write ("============================================
");
While (result = patt.exe c (str ))! = Null ){
Document. write (patt. lastIndex +"
");
Document. write (result. constructor. name +"
");
Document. write (result. length +"
");
Document. write (result [0] +"
");
Document. write (result. index +"
");
Document. write (result. input +"
");
Document. write ("============================================
");
}
Document. write (patt. lastIndex +"
");
// Running result:
============================================
Array
W3School
Visit W3School, W3School is a place to study web technology.
============================================
Array
W3School
Visit W3School, W3School is a place to study web technology.
============================================


7. RegExp. test ("str") Method
This method is similar to RegExp.exe c. The difference is that only true or false is returned.
RegExp. lastIndex has the same meaning (this is a RegExp attribute and has nothing to do with using the test method or the exec method)
If the same RegExp uses the test method and exec method successively, you may need to manually set RegExp. lastIndex = 0. These methods share the lastIndex attribute of the same RegExp object.

The Code is as follows:


Var str = "1 Visit W3School, W3School is a place to study web technology .";
Var patt = new RegExp ("W3School", "g ");
Var result;
Result = patt. test (str );
Alert (result); // true
Result = patt. test (str );
Alert (result); // true
Result = patt. test (str );
Alert (result); // false


IE9 +, in later versions of chrome and firefox, str. after match (reg) is executed, lastindex is reset, reg. lastIndex = 0, reg. after test (str) is executed, if the regular expression is not globally matched, The lastindex is reset, re. lastIndex = 0 is in IE8 and below, and re. lastIndex is the position of the last character matching the end of the string plus 1, that is, lastIndex is not reset.

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.