contents   index   previous   next



String match()

syntax:

string.match(pattern)

where:

pattern - a regular expression pattern to find or match in string. May be a regular expression or a value, such as, a string, that may be converted into a regular expression using the RegExp() constructor. For example, both of the following are equivalent:

 

var rtn = "one two three".match(/two/);

var rtn = "one two three".match("two");

return:

array - an array with various elements and properties set depending on the attributes of a regular expression. Returns null if no match is found.

 

description:

This method behaves differently depending on whether pattern has the "g" attribute, that is, on whether the match is global.

 

If the match is not global, string is searched for the first match to pattern. A null is returned if no match is found. If a match is found, the return is an array with information about the match. Element 0 has the text matched. Elements 1 and following have the text matched by sub patterns in parentheses. The element numbers correspond to group numbers in regular expression reference characters and regular expression replacement characters. The array has two extra properties: index and input. The property index has the position of the first character of the text matched, and input has the target string.

 

If the match is global, string is searched for all matches to pattern. A null is returned if no match is found. If one or more matches are found, the return is an array in which each element has the text matched for each find. There are no index and input properties. The length property of the array indicates how many matches there were in the target string.

 

If any matches are made, appropriate RegExp object static properties, such as RegExp.leftContext, RegExp.rightContext, RegExp.$n, and so forth are set, providing more information about the matches.

 

see:

RegExp exec(), String replace(), String search(), Regular expression replacement characters, RegExp object static properties

 

example:

   // not global

var pat = /(t(.)o)/;

var str = "one two three tio one";

   // rtn == "two"

   // rtn[0] == "two"

   // rtn[1] == "two"

   // rtn[2] == "w"

   // rtn.index == 4

   // rtn.input == "one two three two one"

rtn = str.match(pat);

 

   // global

var pat = /(t(.)o)/g;

var str = "one two three tio one";

   // rtn[0] == "two"

   // rtn[1] == "tio"

   // rtn.length == 2

rtn = str.match(pat);

 


String replace()