JavaScript test, search, replace, split regular usage

Source: Internet
Author: User
Tags first string

Match method
Performs a lookup on a string using the regular expression pattern and returns the result that contains the lookup as an array.
Stringobj.match (RGEXP)
Parameters
Stringobj
Required option. A string object or string literal to find it.
Rgexp
Required option. Is the 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 match's expression matches the global tag G, all occurrences will appear without looping, but all matches will not contain child matches.
Example 1:
function Matchdemo () {var r, re;//declaring 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 four matches for all "ain" occurrences, r[0], r[1], r[2, r[3]. But there is no child match 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 searched;
Index: the location (bit) where the result is matched;
Lastinput: The position of the next match result;
Arr: result value, Arr[0] Full match result, arr[1,2 ...] Matches the child of the expression inside (), from left to right for 1,2 ....
Example 2:
Copy code code as follows:
function Regexptest () {
var src= "Http://sumsung753.blog.163.com/blog/I Love you!";
var re =/w+/g; Note that G matches 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 second loop once will make the re look for the next match in G action.
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:
0-1:i//0 is the location of Index,i, where 1 is the 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
Description: According to the manual, EXEC returns only the first value of the matching result, for example, if the previous example does not use a while loop, it returns only ' I ' (Although the I space after love and you are consistent with the expression), no matter the RE expression is used without global tag G. However, if you set the global tag for a regular expression g,exec start the lookup from the location indicated by the value lastindex. If the global flag is not set, EXEC ignores the lastindex value and starts the search from the beginning of the string. Using this feature, you can repeatedly call exec to iterate through all the matches, equivalent to match with the G flag.
Of course, if the regular expression forgets to use G, and the loop (for example: while, the for, and so on), exec loops the first one each time, causing a dead loop. The
Exec's output will contain child matches.
Example 3:
Copy code code as follows:
function Execdemo () {
var r, re;//declaring 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 searched. The
Rgexp.test (str)
parameter
Rgexp
must be selected. A regular expression object that contains the regular expression pattern or the available flags.
Str
must be selected. The string on which to test the lookup. The
Description
test method checks whether the string matches the given regular expression pattern, returns true if it is, or returns false.
Example 4:
Copy code code as follows:
function Testdemo (re, s) {
var S1;
if (re.test (s))
S1 = "matching regular";
Else
S1 = "mismatched regular";
Return ("" "+ S +" "" + S1 + "'" + Re.source + "");
}
Window.onload = document.write (Testdemo (/ab/, ' cdef '));

Output result: ' Cdef ' does not match regular type ' AB '
Note: Test () inherits the Lastindex property of the regular expression, which should be noted when matching global flag G.
Example 5:
Copy code code as follows:
function Testdemo () {
var r, re; Declare 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 results:
True
False
True
When you call Test () the second time, lastindex points to the next match at location 1, so the second match is unsuccessful, lastindex points back to 0, and then the third time it is matched again. The following example shows the Lastindex property of test:
Example 6:
Copy code code as follows:
function Testdemo () {
var r, re; Declare 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: The Lastindex property of test () is again pointed to 0,re.lastindex = 0 each time;

Search method
Returns the position (offset) of the first substring that matches the lookup content of the regular expression.
Stringobj.search (RGEXP)
Parameters
Stringobj
Required option. The string object or string literal to find on.
Rgexp
Required option. A regular expression object that contains the regular expression pattern and the available flags.
Note: Returns the offset bit at the beginning of the Fu Zhi if found, or 1.
Example 6:
Copy code code as follows:
function Searchdemo () {
var r, re; Declare 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); Find the 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 a string that is replaced with text based on a regular expression.
Stringobj.replace (Rgexp, ReplaceText)
Parameters
Stringobj
Required option. The string object or string literal to perform the substitution. The string is not modified by the Replace method.
Rgexp
Required option. Is the regular expression object that contains the regular expression pattern or the available flags. It can also be a String object or text. If Rgexp is not a regular expression object, it is converted to a string and the exact lookup is made; 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 in that object. In the Jscript 5.5 or later version, the ReplaceText parameter can also be a function that returns the replacement text.
Description
The result of the Replace method is a copy of the Stringobj object that completes the specified replacement. The meaning is specified as a replacement for the matching item, and the other invariant is returned as stringobj.
ECMAScript v3 stipulates that the parameter replacement of the replace () method can be a function rather than 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 argument 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. function as a parameter can be more complex operations.
Example 7:
Copy code code as follows:
function f2c (s) {
var test =/(d+ (. d*)?) fb/g; The possible modes of Fahrenheit temperature are: 123F or 123.4F. Note that G mode is used here.
Return (S.replace
(Test,
function (regstr,$1,$2,$3,newstrobj) {
Return ("<br/>" + regstr + "<br/>" + ($1-32) * 1/2) + "C" + "<br/>" +//The following two lines to replace
$ + "<br/>" + $ + "<br/>" + newstrobj + "<br/>");
}
)
);
}
document.write (F2C ("water:32.2f and oil:20.30f."));

Output:
Water://does not match regular characters, output
32.2F//The original string of the first string corresponding to the regular REGSTR
0.10000000000000142C/// The replacement result of the first child pattern match for the first string that matches the regular match is
. 2//replacement result of the second child pattern Match of the first string that matches the regular match, where we have not replaced it with $
7// The offset of the first substring of the first string that matches the regular match appears $
water:32.2f and oil:20.30f.//original string newstrobj
and Oil://No matching characters
20.30F// The original string of the second string that matches the regular
-5.85c//The first child of the second string that matches the regular match and the matching replacement result
. 30//The replacement result of the second child pattern Match of the second string matching the regular match, where we have not replaced it with the
22//The offset of the first substring of the second string that matches the regular is
water:32.2f and oil:20.30f.//The original string
.//does not match regular characters
The above function parameters we all used it. In practice, we only have to replace the XXF with the XXC, according to the requirements, we do not need to write so many parameters.
Example 8:
Copy code code as follows:
function f2c (s) {
var test =/(d+ (. d*)?) fb/g; The possible modes of Fahrenheit temperature are: 123F or 123.4F
return (s.replace
(test,
Function (strobj,$1) {
return (($1-32) * 1/2) + "C") ;
}
)
);
}
document.write (f2c ("water:32.2f and oil:20.30f.");

Output: water:0.10000000000000142c and oil: -5.85c.
More applications:
Example 9:
Copy code code 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 a substring and returns the result as an array of strings.
Stringobj.split ([separator[, limit]])
Parameters
Stringobj
Required option. The String object or text to be exploded. The object is not modified by the split method.
Separator
Options available. A string or regular expression object that identifies whether one or more characters are used to delimit a string. If this option is omitted, an array of single elements containing the entire string is returned.
Limit
Options available. This value is used to limit the number of elements returned in an array.
Description
The result of the split method is an array of strings, where each occurrence of separator in the stingobj is decomposed. Separator is not returned as part of any array element.
Example 10:
Copy code code as follows:
function Splitdemo () {
var s, SS;
var s = "The rain in Spain falls mainly in the plain.";
A regular expression, separated by an s that is not written in large.
SS = S.split (/s/i);
return (SS);
}
document.write (Splitdemo ());

Output: The rain in, pain fall, mainly in the plain.

The exec () method, Match () method and search () method of JS Regular expression

First look at the code:

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));

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.