str.match(regexp)
인자
regexp
정규식 개체입니다. RegExp가 아닌 객체 obj가 전달되면,
new RegExp(obj)
를 사용하여 암묵적으로 RegExp
로 변환됩니다. 매개변수를 전달하지 않고 match()를 사용하면, 빈 문자열:[""]이 있는 Array
가 반환됩니다.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'는 완전한 매치 상태임. // 'Chapter 3.4.5.1'는 '(chapter \d+(\.\d)*)' 부분에 의해 발견된 것임. // '.1' 는 '(\.\d)'를 통해 매치된 마지막 값임. // 'index' 요소가 (22)라는 것은 0에서부터 셀 때 22번째 위치부터 완전 매치된 문자열이 나타남을 의미함. // 'input' 요소는 입력된 원래 문자열을 나타냄.
글로벌(g), 대소문자 무시(i)
var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; var regexp = /[A-E]/gi; // A~E를 찾는데 대소문자 무시하고 찾아라. var matches_array = str.match(regexp); console.log(matches_array); // ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e']
정규표현식이 아닌 obj 전달 시 암묵적으로 Regex(obj)로 변환함
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"는 문자열임. ["number"]를 반환함. str1.match(NaN); // NaN 타입은 숫자형임. ["NaN"]을 반환함. str1.match(Infinity); // Infinity 타입은 숫자형임. ["Infinity"]를 반환함. str1.match(+Infinity); // ["Infinity"]를 반환함. str1.match(-Infinity); // ["-Infinity"]를 반환함. str2.match(65); // ["65"]를 반환함 str2.match(+65); // 플러스 기호가 붙은 숫자형. ["65"]를 반환함. str3.match(null); // ["null"]을 반환함.