match() method retrieves the result of matching a string against a regular expression .

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

句法

str.match(regexp)
					

参数

regexp

A regular expression object.

regexp is a non- RegExp object, it is implicitly converted to a RegExp by using new RegExp( regexp ) .
If you don't give any parameter and use the match() method directly, you will get an Array with an empty string: [""] .

返回值

Array whose contents depend on the presence or absence of the global ( g ) flag, or null if no matches are found.

  • g flag is used, all results matching the complete regular expression will be returned, but capturing groups will not.
  • g flag is not used, only the first complete match and its related capturing groups are returned. In this case, the returned item will have additional properties as described below.

Additional properties

As explained above, some results contain additional properties as described below.

groups
An object of named capturing groups whose keys are the names and values are the capturing groups or undefined if no named capturing groups were defined. See Groups and Ranges 了解更多信息。
index

The index of the search at which the result was found.

input

A copy of the search string.

描述

If the regular expression does not include the g flag, str.match() will return the same result as RegExp.exec() .

Other methods

范例

Using match()

In the following example, match() is used to find ' 章节 ' followed by 1 or more numeric characters followed by a decimal point and numeric character 0 or more times.

The regular expression includes the i flag so that upper/lower case differences will be ignored.

const str = 'For more information, see Chapter 3.4.5.1';
const re = /see (chapter \d+(\.\d)*)/i;
const found = str.match(re);
console.log(found);
// logs [ 'see Chapter 3.4.5.1',
//        'Chapter 3.4.5.1',
//        '.1',
//        index: 22,
//        input: 'For more information, see Chapter 3.4.5.1' ]
// 'see Chapter 3.4.5.1' is the whole match.
// 'Chapter 3.4.5.1' was captured by '(chapter \d+(\.\d)*)'.
// '.1' was the last value captured by '(\.\d)'.
// The 'index' property (22) is the zero-based index of the whole match.
// The 'input' property is the original string that was parsed.
					

Using global and ignore case flags with match()

The following example demonstrates the use of the global and ignore case flags with match() . All letters A through E and a through e are returned, each its own element in the array.

const str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
const regexp = /[A-E]/gi;
const matches_array = str.match(regexp);
console.log(matches_array);
// ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e']
					

注意: 另请参阅 String.prototype.matchAll() and Advanced searching with flags .

Using named capturing groups

In browsers which support named capturing groups, the following code captures " fox " or " cat " into a group named " animal ":

const paragraph = 'The quick brown fox jumps over the lazy dog. It barked.';
const capturingRegex = /(?<animal>fox|cat) jumps over/;
const found = paragraph.match(capturingRegex);
console.log(found.groups); // {animal: "fox"}
					

Using match() with no parameter

const str = "Nothing will come of nothing.";
str.match();   // returns [""]
					

A non-RegExp object as the parameter

When the regexp parameter is a string or a number, it is implicitly converted to a RegExp by using new RegExp( regexp ) .

If it is a positive number with a positive sign, RegExp() will ignore the positive sign.

const str1 = "NaN means not a number. Infinity contains -Infinity and +Infinity in JavaScript.",
    str2 = "My grandfather is 65 years old and My grandmother is 63 years old.",
    str3 = "The contract was declared null and void.";
str1.match("number");   // "number" is a string. returns ["number"]
str1.match(NaN);        // the type of NaN is the number. returns ["NaN"]
str1.match(Infinity);   // the type of Infinity is the number. returns ["Infinity"]
str1.match(+Infinity);  // returns ["Infinity"]
str1.match(-Infinity);  // returns ["-Infinity"]
str2.match(65);         // returns ["65"]
str2.match(+65);        // A number with a positive sign. returns ["65"]
str3.match(null);       // returns ["null"]
					

规范

规范
ECMAScript (ECMA-262)
The definition of 'String.prototype.match' in that specification.

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
match Chrome 1 Edge 12 Firefox 1 IE 4 Opera 4 Safari 1 WebView Android 1 Chrome Android 18 Firefox Android 4 Opera Android 10.1 Safari iOS 1 Samsung Internet Android 1.0 nodejs 0.1.100

图例

完整支持

完整支持

另请参阅

元数据

  • 最后修改:
  1. 标准内置对象
  2. String
  3. 特性
    1. String 长度
  4. 方法
    1. String.fromCharCode()
    2. String.fromCodePoint()
    3. String.prototype.anchor()
    4. String.prototype.big()
    5. String.prototype.blink()
    6. String.prototype.bold()
    7. String.prototype.charAt()
    8. String.prototype.charCodeAt()
    9. String.prototype.codePointAt()
    10. String.prototype.concat()
    11. String.prototype.endsWith()
    12. String.prototype.fixed()
    13. String.prototype.fontcolor()
    14. String.prototype.fontsize()
    15. String.prototype.includes()
    16. String.prototype.indexOf()
    17. String.prototype.italics()
    18. String.prototype.lastIndexOf()
    19. String.prototype.link()
    20. String.prototype.localeCompare()
    21. String.prototype.match()
    22. String.prototype.matchAll()
    23. String.prototype.normalize()
    24. String.prototype.padEnd()
    25. String.prototype.padStart()
    26. String.prototype.repeat()
    27. String.prototype.replace()
    28. String.prototype.replaceAll()
    29. String.prototype.search()
    30. String.prototype.slice()
    31. String.prototype.small()
    32. String.prototype.split()
    33. String.prototype.startsWith()
    34. String.prototype.strike()
    35. String.prototype.sub()
    36. String.prototype.substr()
    37. String.prototype.substring()
    38. String.prototype.sup()
    39. String.prototype.toLocaleLowerCase()
    40. String.prototype.toLocaleUpperCase()
    41. String.prototype.toLowerCase()
    42. String.prototype.toSource()
    43. String.prototype.toString()
    44. String.prototype.toUpperCase()
    45. String.prototype.trim()
    46. String.prototype.trimEnd()
    47. String.prototype.trimStart()
    48. String.prototype.valueOf()
    49. String.prototype[@@iterator]()
    50. String.raw()
  5. 继承:
  6. Function
  7. 特性
    1. Function.arguments
    2. Function.caller
    3. Function.displayName
    4. Function.length
    5. Function.name
  8. 方法
    1. Function.prototype.apply()
    2. Function.prototype.bind()
    3. Function.prototype.call()
    4. Function.prototype.toSource()
    5. Function.prototype.toString()
  9. Object
  10. 特性
    1. Object.prototype.__proto__
    2. Object.prototype.constructor
  11. 方法
    1. Object.prototype.__defineGetter__()
    2. Object.prototype.__defineSetter__()
    3. Object.prototype.__lookupGetter__()
    4. Object.prototype.__lookupSetter__()
    5. Object.prototype.hasOwnProperty()
    6. Object.prototype.isPrototypeOf()
    7. Object.prototype.propertyIsEnumerable()
    8. Object.prototype.toLocaleString()
    9. Object.prototype.toSource()
    10. Object.prototype.toString()
    11. Object.prototype.valueOf()
    12. Object.setPrototypeOf()