js regular functions match, exec, test, search, replace, split the use.

Reprinted from the product is slightly Library:  http://www.pinlue.com/article/2020/03/0414/149979963427.html

 

match method

Use regular expression pattern to perform a search string, and the result of the lookup contains returned as an array.

stringObj.match(rgExp)

parameter

stringObj

required. Its String object or text string to find.

rgExp

required. It is positive with the regular expression pattern and applicable flags expression object. It can also be a variable name or text string containing a regular expression pattern and applicable flags.

The remaining instructions and exec as if the match is a different expression matching the global mark g will appear all the matches, and not cycle, but will not include all matching sub-matches.

Example 1:

function MatchDemo () {var r, re; // declare variables. var s = "The rain in Spain falls mainly in the plain"; re = / (a) in / ig; // Create a regular expression pattern. r = s.match (re); // try to match the search string. document.write (r); // returns array contains all four matching "ain" appears, r [0], r [1], r [2], r [3]. // But no child matches a. } Output: ain, ain, ain, ain

Methods exec

Expression pattern are being used to find a string, and returns the first value in the lookup result (array), if the match fails, return null.

rgExp.exec(str)

parameter

rgExp

required. It contains regular expression pattern and applicable flags regular expression object.

str

required. In which to perform a lookup of the String object or string literal.

Returns an array:

input: the value of the entire search string;

index: where the matching position result (position);

lastInput: the position of the next matching result;

arr: result value, arr [0] match-result, ARR [1,2 ...] submatch expression within () is, from left to right as 1, 2 ....

Example 2:

Copy the code code is as follows:

function RegExpTest(){

var src="http://sumsung753.blog.163.com/blog/I love you!";

var re = / \ w + / g; // g note text will match without ever returns only the first match.

was arr;

while ((arr = re.exec (src))! = null) {// exec so arr return the first match, while a match cycle time will re looking at the role g.

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 for the index, i location, a location 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

Note: According to the manual, exec returns a value of only the first match results, such as the cases of the while loop if not, it will return only "I" (despite the love i the space and you are in line with expressions), whether by re expression no global mark g. But if the regular expression to set global mark g, exec began to look lastIndex value from the position indicated. If the global flag is not set, exec ignores the value of lastIndex, start the search from the beginning of the string. Using this feature you can repeatedly call exec through all the match, equivalent to the match has the g flag.

Of course, if you forget to use regular expressions g, but with a loop (for example: while, for, etc.), exec will always first cycle, resulting in an endless loop.

The output will contain sub-exec matches.

Example 3:

Copy the code code is as follows:

function execDemo(){

var r, re; // declare variables.

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

It returns a Boolean value that indicates the search string matches the given regular expression.

rgexp.test(str)

parameter

rgexp

required. It contains regular expression pattern or logo available regular expression object.

str

required. To test the search string on it.

Explanation

Regular expression pattern test method checks whether the given string match, returns true if it is, otherwise returns false.

Example 4:

Copy the code code is as follows:

function TestDemo(re, s){

was s1;

if (re.test(s))

s1 = "match the regular expression";

else

s1 = "does not match the regular expression";

return(""" + s + """ + s1 + """+ re.source + """);

}

window.onload = document.write(TestDemo(/ab/,"cdef"));

Output Results: "cdef" does not match the regular expression "ab"

Note: test () inherited lastIndex property of the regular expression, the expression global flag g in the match when it should be noted.

Example 5:

Copy the code code is as follows:

function testDemo(){

var r, re; // declare variables.

var s = "I";

re = / I / ig; // create 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:

true

false

true

When the second call test () when a match point at lastIndex location 1, the second unsuccessful match, lastIndex redirected, equal to the third match again. The following example shows the lastIndex property test:

Example 6:

Copy the code code is as follows:

function testDemo(){

var r, re; // declare variables.

var s = "I";

re = / I / ig; // create 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

Solution: The test () lastIndex property of each redirected 0, re.lastIndex = 0;

search method

Regular expression search and returns the position of the first substring matching content (offset bits).

stringObj.search(rgExp)

parameter

stringObj

required. String object to be looking at it on or string literal.

rgExp

required. It contains regular expression pattern and applicable flags regular expression object.

Note: If you find a child character returns to the offset position at the beginning, otherwise -1.

Example 6:

Copy the code code is as follows:

function SearchDemo(){

var r, re; // declare variables.

var s = "The rain in Spain falls mainly in the plain.";

re = / falls / i; // create a regular expression pattern.

re2 = / tom / i;

r = s.search (re); // search string.

r2 = s.search(re2);

return ( "r:" + r + "; r2:" + r2); // Returns a Boolean result.

}

document.write(SearchDemo());

Output: r: 18; r2: -1

replace method

The string of returned copying regular expression character replacement.

stringObj.replace(rgExp, replaceText)

parameter

stringObj

required. To perform the replacement String object or string literal. The string is not modified replace method.

rgExp

required. Is positive with the regular expression pattern or logo is available expression object. It can also be a String object or text. If rgExp not a regular expression object, it is converted to a string and accurate look; do not try to convert a string as a regular expression.

replaceText

required. Is a String object or text string, for each matched stringObj rgExp position in both of the object to be replaced with the text contained. In Jscript 5.5 or later, replaceText parameters may also be a function that returns the replacement text.

Explanation

Results replace method is a complete copy of the specified object stringObj alternative. Means for matching the specified item is replaced, the other is returned as constant as StringObj.

ECMAScript v3 predetermined, parameter replacement replace () method may be a function instead of a string. In this case, the function gets called for each match, it returns the string will be used as replacement text. The first parameter is a function of the pattern string matching. The next parameter is a string and pattern matching subexpression, there may be zero or more of such parameters. The next argument is an integer, the position statement appears in stringObject the match. The last parameter is stringObject itself. The result of each sub-replacement string into a corresponding string value matching the return value of the function call. Function as a reference can be made more complex operations.

Example 7:

Copy the code code is as follows:

function f2c(s) {

var test = /(\d+(\.\d*)?)F\b/g; // Fahrenheit possible modes are described: 123F or 123.4F. Note that here with the g mode

return(s.replace

(test,

function(Regstr,$1,$2,$3,newstrObj) {

return (( "<br/>" + Regstr + "<br/>" + ($ 1-32) * 1/2) + "C" + "<br/>" + // replace these two lines

$2 +"<br/>" + $3 +"<br/>" + newstrObj +"<br/>" );

}

)

);

}

document.write(f2c("Water: 32.2F and Oil: 20.30F."));

Output:

Water: // does not match with the regular characters, according to the original character output

Original string Regstr 32.2F // first string match the regular

Alternatively result 0.10000000000000142C // first subpattern first string matches the regular matching $ 1

.2 // matches the regular pattern of a second sub-string matches substitution result, here we do not replace it with $ 2

The first sub-offset matches occurring 7 // first string match the regular $ 3

Water: 32.2F and Oil:. 20.30F // original string newstrObj

and Oil: // characters do not match the regular

20.30F // original string that matches the regular second string

Alternatively the first sub pattern matching results of the regular -5.85C // matches the second string

.30 // the regular match of the second string of the second sub-pattern matching replace result items, here we do not replace it

The first sub-match offset 22 to match the regular // second string occurring

Water: 32.2F and Oil:. 20.30F // original string

// does not match the regular characters

All the above arguments we used the. In practice, we only use the xxF replaced xxC, upon request, we do not have to write so many parameters.

Example 8:

Copy the code code is as follows:

function f2c(s) {

var test = /(\d+(\.\d*)?)F\b/g; // Fahrenheit possible modes are described: 123F 123.4F or

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 the code 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($2 +"/" + $1);

}

)

);

}

document.write(f2c("today: 2011-03-29"));

Output: today: 03/2011

split method

A string is divided into sub-strings, and then return the result as an array of strings.

stringObj.split([separator[, limit]])

parameter

stringObj

required. String object or text to be broken down. The object is not modified split method.

separator

Optional. String or a regular expression object, which identifies the partition string is used for one or multiple characters. If omitted, returns a single-element array containing the entire string.

limit

Optional. This value is used to limit the number of elements in the array returned.

Explanation

Results split method is a string array, should be carried out in each position stingObj decomposition of the separator occurs. Without any separator array element return portion.

Example 10:

Copy the code 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 do not write regardless of s.

ss = s.split(/s/i);

return(ss);

}

document.write(SplitDemo());

输出:The rain in ,pain fall, mainly in the plain.

js regex of exec () method, match () method, and a search () method

Look at the code:

var sToMatch = "test, Tes, tst, tset, Test, Tesyt, sTes";

var REES = / is / gi;

alert(reEs.exec(sToMatch));

alert(sToMatch.match(reEs));

alert(sToMatch.search(reEs));

Three pop-up box as follows:

 

 

The results are analyzed as follows:

1, RegExp the exec () method, a string argument and returns an array, the first entry in the array is the first match; the other is the reverse reference. Therefore, results of the first return the first matching value ES (case insensitive).

2, String object has a match () method, which returns all the matching data contained in the string. This method is called string objects, and pass it a RegExp object. So the second pop-up statement returns an array of all the regular expression in line.

3, search () method with the indexOf string () somewhat similar, but it uses a RegExp object rather than just a substring. search () method returns the value of the first matching position. So the pop-up third place is "1", that is to match the second character. Note that the search () method does not support global regular expression match (with parameters g).

Published 60 original articles · won praise 52 · views 110 000 +

Guess you like

Origin blog.csdn.net/yihuliunian/article/details/104664071