String.prototype.match()当字符串匹配到正则表达式(regular expression)时,match() 方法会提取匹配项。
语法:str.match(regexp);
参数:regexp
一个包含匹配结果的数组,如果没有匹配项,则返回 null。
描述
如果正则表达式没有 g 标志,返回和 RegExp.exec(str) 相同的结果。而且返回的数组拥有一个额外的 input 属性,该属性包含原始字符串。另外,还拥有一个 index 属性,该属性表示匹配结果在原字符串中的索引(以0开始)。
var str = "For more information, see Chapter 3.4.5.1";
var re = /(chapter \d+(\.\d)*)/i;
var found = str.match(re);
console.log(found);
// logs ["Chapter 3.4.5.1", "Chapter 3.4.5.1", ".1"]
// "Chapter 3.4.5.1" is the first match and the first value
// remembered from (Chapter \d+(\.\d)*).
// ".1" is the last value remembered from (\.\d).
语法:str.match(regexp);
参数:regexp
一个正则表达式对象。如果传入一个非正则表达式对象,
则会隐式地使用 new RegExp(obj) 将其转换为正则表达式对象。
返回值:array一个包含匹配结果的数组,如果没有匹配项,则返回 null。
描述
如果正则表达式没有 g 标志,返回和 RegExp.exec(str) 相同的结果。而且返回的数组拥有一个额外的 input 属性,该属性包含原始字符串。另外,还拥有一个 index 属性,该属性表示匹配结果在原字符串中的索引(以0开始)。
如果正则表达式包含 g 标志,则该方法返回一个包含所有匹配结果的数组。如果没有匹配到,则返回 null。
var str = "For more information, see Chapter 3.4.5.1";
var re = /(chapter \d+(\.\d)*)/i;
var found = str.match(re);
console.log(found);
// logs ["Chapter 3.4.5.1", "Chapter 3.4.5.1", ".1"]
// "Chapter 3.4.5.1" is the first match and the first value
// remembered from (Chapter \d+(\.\d)*).
// ".1" is the last value remembered from (\.\d).