JS regular function match, exec, test, search, replace, split use the introduction set

Source: Internet
Author: User
Tags first string javascript array

Match Method
Use the regular expression pattern to perform a lookup on a string and return the result that contains the lookup as an array.
Stringobj.match (RGEXP)
Parameters
Stringobj
Required option. A string object or string literal on which to find.
Rgexp
Required option. is a regular expression object that contains the regular expression pattern and the available flags. It can also be a variable name or string literal that contains the regular expression pattern and the available flags.
The rest of the instructions are the same as exec, except that if the match expression matches the global tag G, all occurrences will appear without loops, but all matches will not contain sub-matches.
Example 1:
function Matchdemo () {var r, re;//declare variable. var s = "The rain in Spain falls mainly in the plain"; Re =/(a) in/ig; Creates a regular expression pattern. r = S.match (re); Try to match the search string. document.write (R); The returned array contains all four occurrences of "Ain", R[0], r[1], r[2], r[3]. But no child matches a. Output Result: Ain,ain,ain,ain
exec method
Finds in a string with a regular expression pattern, returns the first value (array) of the lookup result, and returns null if the match fails.
Rgexp.exec (str)
Parameters
Rgexp
Required option. A regular expression object that contains the regular expression pattern and the available flags.
Str
Required option. The string object or string literal in which to perform the lookup.
The returned array contains:
Input: The value of the entire string being looked up;
Index: The position (bit) where the match results are located;
Lastinput: The position of the next matching result;
Arr: result value, Arr[0] Full match result, arr[1,2 ...] is a sub-match of () within an expression, from left to right ....
Example 2:
Copy CodeThe code is as follows:
function Regexptest () {
var src= "Http://sumsung753.blog.163.com/blog/I Love you!";
var re =/\w+/g; Note that G will match the full text, and will never return only the first match.
var arr;
while (arr = re.exec (src))!=null) {//exec causes Arr to return the first match, while the loop once causes the RE to look for the next match in the G function.
document.write (Arr.index + "-" + Arr.lastindex + ":" + arr + "<br/>");
For (key in arr) {
document.write (key + "=" + Arr[key] + "<br/>");
}
document.write ("<br/>");
}
}
Window.onload = Regexptest ();
Output Result:
0-1:i//0 for index,i position, 1 for next match
Input=>i Love you!
Index=>0
Lastindex=>1
0=>i
2-6:love
Input=>i Love you!
Index=>2
Lastindex=>6
0=>love
7-10:you
Input=>i Love you!
Index=>7
Lastindex=>10
0=>you
Note: According to the manual, EXEC returns only the first value of the matching result, such as the previous example if you do not use a while loop, will only return ' I ' (although the I space after love and you both conform to the expression), regardless of the RE expression with no global tag G. However, if a global tag is set for the regular expression g,exec the lookup begins at the position indicated by the value of LastIndex. If the global flag is not set, Exec ignores the value of LastIndex and starts the search from the beginning of the string. With this feature you can repeatedly call exec to traverse all matches, equivalent to match with the G flag.
Of course, if the regular expression forgets to use the G, but also uses the loop (for example: while, for and so on), the exec will loop each time first, causes the dead loop.
The output of Exec will contain sub-matches.
Example 3:
Copy CodeThe code is as follows:
function Execdemo () {
var r, re; Declares a variable.
var s = "The rain in Spain falls mainly in the plain";
Re =/[\w]* (AI) n/ig;
R = re.exec (s);
document.write (R + "<br/>");
For (key in R) {
document.write (key + "-" + R[key] + "<br/>");
}
}
Window.onload = Execdemo ();
Output:
Rain,ai
Input-the rain in Spain falls mainly in the plain
Index-4
LastIndex-8
0-rain
1-ai
Test method
Returns a Boolean value that indicates whether the given regular expression is matched in the string being looked up.
Rgexp.test (str)
Parameters
Rgexp
Required option. A regular expression object that contains a regular expression pattern or an available flag.
Str
Required option. The string on which to test the lookup.
Description
The test method checks whether the string matches the given regular expression pattern, returns true if it is, or returns false.
Example 4:
Copy CodeThe code is as follows:
function Testdemo (Re, s) {
var S1;
if (Re.test (s))
S1 = "matching regular";
Else
S1 = "does not match the regular formula";
Return ("'" + S + "'" + S1 + "'" + Re.source + "'");
}
Window.onload = document.write (Testdemo (/ab/, ' cdef '));
Output: ' Cdef ' does not match regular type ' AB '
Note: Test () inherits the Lastindex property of the regular expression, which should be noted when matching the global flag G.
Example 5:
Copy CodeThe code is as follows:
function Testdemo () {
var r, re; Declares a variable.
var s = "I";
re =/i/ig; Creates a regular expression pattern.
document.write (Re.test (s) + "<br/>"); Returns a Boolean result.
document.write (Re.test (s) + "<br/>");
document.write (Re.test (s));
}
Testdemo ();
Output Result:
True
False
True
When the second call to test (), lastindex points to the next match location 1, so the second match is not successful, lastindex again points to 0, is equal to the third and re-match. The following example shows the Lastindex property of test:
Example 6:
Copy CodeThe code is as follows:
function Testdemo () {
var r, re; Declares a variable.
var s = "I";
re =/i/ig; Creates a regular expression pattern.
document.write (Re.test (s) + "<br/>"); Returns a Boolean result.
document.write (Re.lastindex); Returns a Boolean result.
}
Testdemo ();
Output:
True
1
Workaround: Each time the LastIndex property of test () is re-directed to 0,re.lastindex = 0;

Search method
Returns the position (partial shift) of the first substring that matches the regular expression find content.
Stringobj.search (RGEXP)
Parameters
Stringobj
Required option. The string object or string literal on which to look.
Rgexp
Required option. A regular expression object that contains the regular expression pattern and the available flags.
Note: If found, returns the offset bit at the beginning of the Fu Zhi, otherwise returns-1.
Example 6:
Copy CodeThe code is as follows:
function Searchdemo () {
var r, re; Declares a variable.
var s = "The rain in Spain falls mainly in the plain.";
re =/falls/i; Creates a regular expression pattern.
Re2 =/tom/i;
r = S.search (re); Finds a string.
r2 = S.search (Re2);
Return ("R:" + R + "; R2:" + R2); Returns a Boolean result.
}
document.write (Searchdemo ());
Output: r:18;r2:-1
Replace method
Returns the copy of the string after the literal substitution based on the regular expression.
Stringobj.replace (Rgexp, ReplaceText)
Parameters
Stringobj
Required option. A string object or string literal to perform the substitution. The string is not modified by the Replace method.
Rgexp
Required option. is a regular expression object that contains a regular expression pattern or an available flag. It can also be a String object or literal. If Rgexp is not a regular expression object, it will be converted to a string, and the exact lookup is done, and do not attempt to convert the string to a regular expression.
ReplaceText
Required option. is a string object or string literal, and the position in each matching rgexp in Stringobj is replaced with the text contained by the object. In Jscript 5.5 or later, the ReplaceText parameter can also be a function that returns alternate text.
Description
The result of the Replace method is a copy of the Stringobj object that completed the specified substitution. means that the matching item is specified for substitution, and the other remains unchanged as the stringobj return.
ECMAScript v3 stipulates that the parameter replacement of the replace () method can be a function instead of a string. In this case, each match calls the function, and the string it returns is used as the replacement text. The first parameter of the function is a string that matches the pattern. The next parameter is a string that matches the subexpression in the pattern and can have 0 or more of these parameters. The next argument is an integer that declares where the match appears in the Stringobject. The last parameter is the stringobject itself. The result is a string value that replaces each matched substring with the corresponding return value of the function call. Functions can be used for more complex operations.
Example 7:
Copy CodeThe code is as follows:
function f2c (s) {
var test =/(\d+ (\.\d*)?) f\b/g; Description Fahrenheit temperature may be: 123F or 123.4F. Note that the G mode is used here.
Return (S.replace
(Test,
function (regstr,$1,$2,$3,newstrobj) {
Return (("<br/>" + regstr + "<br/>" + ($1-32) *) + "C" + "<br/>" +//The following two lines to replace
$ + "<br/>" + $ + "<br/>" + newstrobj + "<br/>");
}
)
);
}
document.write (F2C ("water:32.2f and oil:20.30f.");
Output Result:
Water://does not match the regular character, output by the original character
32.2F//The original string of the first string matched with a regular regstr
0.10000000000000142C//Match the first sub-pattern of the first string that matches the regular match result of the substitution $
.2//matches the result of the second sub-pattern match of the first string matched with a regular, we did not replace it here
7//The first sub-match of the first string that matches the regular one occurs with an offset of $ A
water:32.2f and oil:20.30f. Original String Newstrobj
and oil://characters that do not match the regular
20.30F//The original string of a second string that matches a regular match
-5.85C//matches the first sub-pattern of the second string with a regular match with the replacement result
.30//The substitution result of the second sub-pattern match of the second string that matches the regular match, where we did not replace it
22//The offset from the first sub-match of the second string that matches the regular one
water:32.2f and oil:20.30f. Original string
. Characters that do not match the regular
We've used all of the above function parameters. In practice, we only need to replace XXF with XXC, and on request we do not need to write so many parameters.
Example 8:
Copy CodeThe code is as follows:
function f2c (s) {
var test =/(\d+ (\.\d*)?) f\b/g; Description Fahrenheit temperature Possible mode: 123F or 123.4F
Return (S.replace
(Test,
function (strobj,$1) {
Return ((($1-32) *) + "C");
}
)
);
}
document.write (F2C ("water:32.2f and oil:20.30f.");
Output: water:0.10000000000000142c and oil: -5.85c.
More applications:
Example 9:
Copy CodeThe code is as follows:
function f2c (s) {
var test =/([\d]{4})-([\d]{1,2})-([\d]{1,2})/;
Return (S.replace
(Test,
function ($0,$1,$2,$3) {
Return ($ + "/" + $);
}
)
);
}
document.write (f2c ("today:2011-03-29"));
Output: today:03/2011
Split method
Splits a string into substrings and returns the result as an array of strings.
Stringobj.split ([separator[, limit]])
Parameters
Stringobj
Required option. The String object or text to be decomposed. The object is not modified by the split method.
Separator
Options are available. A string or regular expression object that identifies whether one or more characters are used when separating the string. If this option is omitted, a single element array containing the entire string is returned.
Limit
Options are available. This value is used to limit the number of elements in the returned array.
Description
The result of the split method is an array of strings, which are decomposed in the stingobj where each occurrence of the separator occurs. Separator is not returned as part of any array element.
Example 10:
Copy CodeThe code is as follows:
function Splitdemo () {
var s, SS;
var s = "The rain in Spain falls mainly in the plain.";
Regular expressions, separated by a large non-writable s.
SS = S.split (/s/i);
return (SS);
}
document.write (Splitdemo ());
Output: The rain in, pain fall, mainly in the plain.

the Exec () method of the JS regular expression, the match () method, and the search () method

Look at the code first:

var stomatch = "Test, Tes, TST, Tset, test, Tesyt, sTes";
var reEs =/es/gi;
Alert (Rees.exec (Stomatch));
Alert (Stomatch.match (reEs));
Alert (Stomatch.search (reEs));

The contents of the three popup boxes are as follows:

The results are analyzed as follows:

1, regexp the Exec () method, has a string parameter, returns an array, the first entry of the array is the first match, the other is a reverse reference. So the first returned result is the first matching value es (case insensitive).

2. The string object has a match () method that returns all the matching data contained in the string. This method invokes a string object and passes it a RegExp object. So the second pop-up statement returns all arrays that conform to the regular expression.

3. The string method of search () is somewhat similar to indexof (), but it uses a RegExp object rather than just a substring. The search () method returns the position of the first matched value. So the third place that pops up is "1", that is, the second character matches. Note that the search () method does not support global matching of regular expressions (with parameter g).

Articles you may be interested in:
    • Fast cloning of JavaScript arrays (slice () function) and array sorting, scrambling, and searching (sort () function)
    • How to use the slice () method in JS
    • JavaScript Array.prototype.slice Instructions for use
    • JS substr, substring and slice use notes
    • JS split the usage and definition of JS split split string array of instance code
    • JS Split Function Usage summary (from getting started to mastering)
    • JS in the Split function by splitting the string array small example
    • JS string intercept function substr substring slice use comparison
    • The slice, Substring, substr functions of JavaScript intercept strings are understood and compared
    • Slice,splice and split three functions that are not easy to distinguish in JavaScript
Reproduced in http://www.jb51.net/article/28007.htm

JS regular function match, exec, test, search, replace, split use the introduction set

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.