이 번역은 완료되지 않았습니다. 이 문서를 번역해 주세요.

 

match() 메서드는 문자열이 정규식과 매치되는 부분을 검색합니다.

문법

str.match(regexp)

매개변수

regexp
정규식 개체입니다.  RegExp가 아닌 객체 obj가 전달되면, new RegExp(obj)를 사용하여 암묵적으로 RegExp로 변환됩니다. 매개변수를 전달하지 않고 match()를 사용하면, 빈 문자열:[""]이 있는 Array가 반환됩니다.

결과 값

문자열이 정규식과 일치하면, 일치하는 전체 문자열을 첫 번째 요소로 포함하는 Array를 반환한 다음 괄호 안에 캡처된 결과가 옵니다. 일치하는 것이 없으면 null이 반환됩니다.

설명

정규식에 g 플래그가 포함되어있지 않으면, str.match() 는 RegExp.exec()와 같은 결과를 반환합니다. 반환된 Array는 원래 문자열의 값을 가지는 input 속성을 포함합니다. 그리고 문자열에서 제로 베이스의 인덱스를 나타내는 index 속성 또한 포함합니다.

정규식에 g 플래그가 포함되어 있으면, 일치는 객체가 아닌 일치하는 하위 문자열을 포함하는 Array를 반환합니다. 캡처된 그룹은 반환되지 않습니다. 일치하는 것이 없으면 null이 반환됩니다.

이것도 보세요: RegExp 메서드

  • 문자열이 정규표현식RegExp과 일치하는지 여부를 알아야할 때, RegExp.test()을 이용해보세요.
  • 일치하는 것 중 제일 첫번째 것만 알고싶을 때, RegExp.exec()을 대신에 사용하고 싶을겁니다.
  • 캡처 그룹을 알고 싶고 전역 플래그가 셋팅되어 있다면, RegExp.exec()을 대신에 사용해야합니다.

예제

 Using match() 사용하기

In the following example, match() is used to find 'Chapter' 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.

var str = 'For more information, see Chapter 3.4.5.1';
var re = /see (chapter \d+(\.\d)*)/i;
var 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.

var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
var regexp = /[A-E]/gi;
var matches_array = str.match(regexp);

console.log(matches_array);
// ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e']

Using match() with no parameter

var str = "Nothing will come of nothing.";

str.match();   // returns [""]

A non-RegExp object as the parameter

When the parameter is a string or a number, it is implicitly converted to a RegExp by using new RegExp(obj). If it is a positive number with a positive sign,the RegExp() method will ignore the positive sign. 

var 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"]

Specifications

Specification Status Comment
ECMAScript 3rd Edition (ECMA-262) Standard Initial definition. Implemented in JavaScript 1.2.
ECMAScript 5.1 (ECMA-262)
The definition of 'String.prototype.match' in that specification.
Standard  
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'String.prototype.match' in that specification.
Standard  
ECMAScript Latest Draft (ECMA-262)
The definition of 'String.prototype.match' in that specification.
Draft  

Browser compatibility

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidiOS SafariSamsung InternetNode.js
Basic supportChrome Full support YesEdge Full support YesFirefox Full support 1IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesEdge Mobile Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes
flags
DeprecatedNon-standard
Chrome No support NoEdge No support NoFirefox No support 1 — 49IE No support NoOpera No support NoSafari No support NoWebView Android No support NoChrome Android No support NoEdge Mobile No support NoFirefox Android No support 4 — 49Opera Android No support NoSafari iOS No support NoSamsung Internet Android No support Nonodejs No support No

Legend

Full support  
Full support
No support  
No support
Non-standard. Expect poor cross-browser support.
Non-standard. Expect poor cross-browser support.
Deprecated. Not for use in new websites.
Deprecated. Not for use in new websites.

Firefox-specific notes

  • flags was a non standard second argument only available in Gecko : str.match(regexp, flags)
  • Starting with Gecko 27 (Firefox 27 / Thunderbird 27 / SeaMonkey 2.24), this method has been adjusted to conform with the ECMAScript specification. When match() is called with a global regular expression, the RegExp.lastIndex property (if specified) will be reset to 0 (bug 501739).
  • Starting with Gecko 39 (Firefox 39 / Thunderbird 39 / SeaMonkey 2.36), the non-standard flags argument is deprecated and throws a console warning (bug 1142351).
  • Starting with Gecko 47 (Firefox 47 / Thunderbird 47 / SeaMonkey 2.44), the non-standard flags argument is no longer supported in non-release builds and will soon be removed entirely (bug 1245801).
  • Starting with Gecko 49 (Firefox 49 / Thunderbird 49 / SeaMonkey 2.46), the non-standard flags argument is no longer supported (bug 1108382).

See also

문서 태그 및 공헌자

이 페이지의 공헌자: Yonnani
최종 변경자: Yonnani,