From da78a9e329e272dedb2400b79a3bdeebff387d47 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:17 -0500 Subject: initial commit --- .../global_objects/regexp/exec/index.html | 188 +++++++++++++++++ .../reference/global_objects/regexp/index.html | 233 +++++++++++++++++++++ .../reference/global_objects/regexp/n/index.html | 66 ++++++ .../global_objects/regexp/regexp/index.html | 114 ++++++++++ .../global_objects/regexp/test/index.html | 129 ++++++++++++ 5 files changed, 730 insertions(+) create mode 100644 files/ko/web/javascript/reference/global_objects/regexp/exec/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/regexp/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/regexp/n/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/regexp/regexp/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/regexp/test/index.html (limited to 'files/ko/web/javascript/reference/global_objects/regexp') diff --git a/files/ko/web/javascript/reference/global_objects/regexp/exec/index.html b/files/ko/web/javascript/reference/global_objects/regexp/exec/index.html new file mode 100644 index 0000000000..4659688c51 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/regexp/exec/index.html @@ -0,0 +1,188 @@ +--- +title: RegExp.prototype.exec() +slug: Web/JavaScript/Reference/Global_Objects/RegExp/exec +tags: + - JavaScript + - Method + - Prototype + - Reference + - RegExp + - 정규 표현식 +translation_of: Web/JavaScript/Reference/Global_Objects/RegExp/exec +--- +
{{JSRef}}
+ +

exec() 메서드는 주어진 문자열에서 일치 탐색을 수행한 결과를 배열 혹은 {{jsxref("null")}}로 반환합니다.

+ +

JavaScript {{jsxref("RegExp")}} 객체는 {{jsxref("RegExp.global", "global")}} 또는 {{jsxref("RegExp.sticky", "sticky")}} 플래그를 설정(/foo/g, /foo/y 등)한 경우 이전 일치의 인덱스를 저장하므로 상태를 가지고(stateful) 있습니다. 이를 내부적으로 사용하여, {{jsxref("String.prototype.match()")}}와는 다르게 (캡처 그룹을 포함한) 문자열 내의 일치 다수를 반복해 순회할 수 있습니다.

+ +

(캡처 그룹을 포함한) 문자열 내의 다수 일치를 수행할 수 있는 보다 간편한 신규 메서드,  {{jsxref("String.prototype.matchAll()")}}이 제안된 상태입니다.

+ +

단순히 true/false가 필요한 경우 {{jsxref("RegExp.prototype.text()")}} 메서드 혹은 {{jsxref("String.prototype.search()")}}를 사용하세요.

+ +
{{EmbedInteractiveExample("pages/js/regexp-prototype-exec.html")}}
+ + + +

구문

+ +
regexObj.exec(str)
+ +

매개변수

+ +
+
str
+
정규 표현식 검색을 수행할 대상 문자열.
+
+ +

반환 값

+ +

정규 표현식이 일치하면, exec() 메서드는 배열(추가 속성 indexinput 포함, 아래 설명을 참고하세요)을 반환하고, 정규 표현식 객체의 {{jsxref("RegExp.lastIndex", "lastIndex")}} 속성을 업데이트합니다. 반환하는 배열은 일치한 텍스트를 첫 번째 원소로, 각각의 괄호 캡처 그룹을 이후 원소로 포함합니다.

+ +

정규표현식 검색에 실패하면, exec() 메서드는 {{jsxref("null")}}을 반환하고 {{jsxref("RegExp.lastIndex", "lastIndex")}}를 0으로 설정합니다.

+ +

설명

+ +

다음과 같은 예제를 고려해보세요.

+ +
// Match "quick brown" followed by "jumps", ignoring characters in between
+// Remember "brown" and "jumps"
+// Ignore case
+let re = /quick\s(brown).+?(jumps)/ig;
+let result = re.exec('The Quick Brown Fox Jumps Over The Lazy Dog');
+ +

다음의 표는 이 스크립트의 결과에 대해 보여줍니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
객체속성/인덱스설명예제
result[0]일치한 전체 문자."Quick Brown Fox Jumps"
[1], ...[n] +

(존재하는 경우) 괄호로 감싼 부분문자열.

+ +

괄호로 감싼 부분문자열 숫자의 제한은 없습니다.

+
+

result[1] === "Brown"

+ +

result[2] === "Jumps"

+
index일치가 문자열에서 위치하는 인덱스. (0 시작)4
input원본 문자열."The Quick Brown Fox Jumps Over The Lazy Dog"
relastIndex +

다음 일치를 시작할 인덱스.

+ +

g를 누락하면 항상 0입니다.

+
25
ignoreCasei 플래그로 대소문자를 무시했는지 여부.true
globalg 플래그로 전역 일치를 수행하는지 여부.true
multilinem 플래그로 여러 줄에 걸친 탐색을 수행하는지 여부.false
source패턴 문자열."quick\s(brown).+?(jumps)"
+ +

예제

+ +

Finding successive matches

+ +

If your regular expression uses the "g" flag, you can use the exec() method multiple times to find successive matches in the same string. When you do so, the search starts at the substring of str specified by the regular expression's {{jsxref("RegExp.lastIndex", "lastIndex")}} property ({{jsxref("RegExp.prototype.test()", "test()")}} will also advance the {{jsxref("RegExp.lastIndex", "lastIndex")}} property). For example, assume you have this script:

+ +
var myRe = /ab*/g;
+var str = 'abbcdefabh';
+var myArray;
+while ((myArray = myRe.exec(str)) !== null) {
+  var msg = 'Found ' + myArray[0] + '. ';
+  msg += 'Next match starts at ' + myRe.lastIndex;
+  console.log(msg);
+}
+
+ +

This script displays the following text:

+ +
Found abb. Next match starts at 3
+Found ab. Next match starts at 9
+
+ +

Note: Do not place the regular expression literal (or {{jsxref("RegExp")}} constructor) within the while condition or it will create an infinite loop if there is a match due to the {{jsxref("RegExp.lastIndex", "lastIndex")}} property being reset upon each iteration. Also be sure that the global flag is set or a loop will occur here also.

+ +

Using exec() with RegExp literals

+ +

You can also use exec() without creating a {{jsxref("RegExp")}} object:

+ +
var matches = /(hello \S+)/.exec('This is a hello world!');
+console.log(matches[1]);
+
+ +

This will log a message containing 'hello world!'.

+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-regexp.prototype.exec', 'RegExp.exec')}}
+ +

브라우저 호환성

+ +
+ + +

{{Compat("javascript.builtins.RegExp.exec")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/regexp/index.html b/files/ko/web/javascript/reference/global_objects/regexp/index.html new file mode 100644 index 0000000000..541d3585db --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/regexp/index.html @@ -0,0 +1,233 @@ +--- +title: RegExp +slug: Web/JavaScript/Reference/Global_Objects/RegExp +tags: + - Constructor + - JavaScript + - Reference + - RegExp + - 정규 표현식 + - 정규식 +translation_of: Web/JavaScript/Reference/Global_Objects/RegExp +--- +
{{JSRef}}
+ +

RegExp 생성자는 패턴을 사용해 텍스트를 판별할 때 사용합니다.

+ +

정규 표현식에 대한 소개는 JavaScript 안내서의 정규 표현식 장을 참고하세요.

+ +

설명

+ +

리터럴 표기법과 생성자

+ +

RegExp 객체는 리터럴 표기법과 생성자로써 생성할 수 있습니다.

+ + + +

다음의 세 표현식은 모두 같은 정규 표현식을 생성합니다.

+ +
/ab+c/i
+new RegExp(/ab+c/, 'i') // 리터럴
+new RegExp('ab+c', 'i') // 생성자
+
+ +

리터럴 표기법은 표현식을 평가할 때 정규 표현식을 컴파일합니다. 정규 표현식이 변하지 않으면 리터럴 표기법을 사용하세요. 예를 들어, 반복문 안에서 사용할 정규 표현식을 리터럴 표기법으로 생성하면 정규 표현식을 매번 다시 컴파일하지 않습니다.

+ +

정규 표현식 객체의 생성자(new RegExp('ab+c'))를 사용하면 정규 표현식이 런타임에 컴파일됩니다. 패턴이 변할 가능성이 있거나, 사용자 입력과 같이 알 수 없는 외부 소스에서 가져오는 정규 표현식의 경우 생성자 함수를 사용하세요.

+ +

생성자의 플래그

+ +

ECMAScript 6부터는 new RegExp(/ab+c/, 'i')처럼, 첫 매개변수가 RegExp이면서 flags를 지정해도 {{jsxref("TypeError")}} ("can't supply flags when constructing one RegExp from another")가 발생하지 않고, 매개변수로부터 새로운 정규 표현식을 생성합니다.

+ +

생성자 함수를 사용할 경우 보통의 문자열 이스케이프 규칙(특수 문자를 문자열에 사용할 때 앞에 역빗금(\)을 붙이는 것)을 준수해야 합니다.

+ +

예를 들어 다음 두 줄은 동일한 정규 표현식을 생성합니다.

+ +
let re = /\w+/
+let re = new RegExp('\\w+')
+ +

Perl  형태의 RegExp 속성

+ +

일부 {{JSxRef("RegExp")}} 속성은 같은 값에 대해 긴 이름과 짧은 (Perl 형태의) 이름 모두 가지고 있습니다. (Perl은 JavaScript가 정규 표현식을 만들 때 참고한 프로그래밍 언어입니다.)  사용하지 않는 RegExp 속성을 참고하세요.

+ +

생성자

+ +
+
{{jsxref("RegExp/RegExp", "RegExp()")}}
+
새로운 RegExp 객체를 생성합니다.
+
+ +

정적 속성

+ +
+
{{jsxref("RegExp.@@species", "get RegExp[@@species]")}}
+
파생 객체를 생성할 때 사용하는 생성자입니다.
+
{{jsxref("RegExp.lastIndex")}}
+
다음 판별을 시작할 인덱스입니다.
+
+ +

인스턴스 속성

+ +
+
{{JSxRef("RegExp.prototype.flags")}}
+
RegExp 객체의 플래그를 담은 문자열입니다.
+
{{JSxRef("RegExp.prototype.dotAll")}}
+
.이 줄 바꿈에 일치하는지 여부를 나타냅니다.
+
{{JSxRef("RegExp.prototype.global")}}
+
정규 표현식이 문자열 내에서 가능한 모든 경우에 일치하는지, 아니면 최초에 대해서만 일치하는지 나타냅니다.
+
{{JSxRef("RegExp.prototype.ignoreCase")}}
+
문자열의 대소문자를 구분하는지 나타냅니다.
+
{{JSxRef("RegExp.prototype.multiline")}}
+
여러 줄에 걸쳐 탐색할 것인지 나타냅니다.
+
{{JSxRef("RegExp.prototype.source")}}
+
패턴을 나타내는 문자열입니다.
+
{{JSxRef("RegExp.prototype.sticky")}}
+
검색이 접착(sticky)되어있는지 나타냅니다.
+
{{JSxRef("RegExp.prototype.unicode")}}
+
Unicode 기능의 활성화 여부입니다.
+
+ +

인스턴스 메서드

+ +
+
{{JSxRef("RegExp.prototype.compile()")}}
+
스크립트 실행 중 정규 표현식을 (다시) 컴파일합니다.
+
{{JSxRef("RegExp.prototype.exec()")}}
+
문자열 매개변수에 대해 검색을 실행합니다.
+
{{JSxRef("RegExp.prototype.test()")}}
+
문자열 매개변수에 대해 판별을 실행합니다.
+
{{JSxRef("RegExp.prototype.toString()")}}
+
객체의 문자열 표현을 반환합니다. {{JSxRef("Object.prototype.toString()")}} 메서드를 재정의합니다.
+
{{JSxRef("RegExp.prototype.@@match()", "RegExp.prototype[@@match]()")}}
+
주어진 문자열에 대해 일치하는 결과를 반환합니다.
+
{{JSxRef("RegExp.prototype.@@matchAll()", "RegExp.prototype[@@matchAll]()")}}
+
주어진 문자열에 대해 일치하는 모든 결과를 반환합니다.
+
{{JSxRef("RegExp.prototype.@@replace()", "RegExp.prototype[@@replace]()")}}
+
주어진 문자열 내의 일치를 새로운 문자열로 대치합니다.
+
{{JSxRef("RegExp.prototype.@@search()", "RegExp.prototype[@@search]()")}}
+
주어진 문자열에 대해 일치하는 인덱스를 반환합니다.
+
{{JSxRef("RegExp.prototype.@@split()", "RegExp.prototype[@@split]()")}}
+
주어진 문자열을 분할해 배열로 반환합니다.
+
+ +

예제

+ +

정규 표현식을 사용해서 데이터 형식 바꾸기

+ +

다음 스크립트에서는 {{jsxref("String")}} 객체의 {{jsxref("String.prototype.replace()", "replace()")}} 메서드를 사용하여 이름 성씨 형태의 이름을 성씨, 이름 형태 바꿔 반환합니다.

+ +

대치 문자열에는 $1$2를 사용하여 정규 표현식 패턴의 각 괄호에 일치한 결과를 받아옵니다.

+ +
let re = /(\w+)\s(\w+)/
+let str = 'John Smith'
+let newstr = str.replace(re, '$2, $1')
+console.log(newstr)
+ +

실행 결과는 "Smith, John"입니다.

+ +

정규 표현식을 사용해서 여러 가지 줄 바꿈 문자가 있는 문자열 나누기

+ +

기본 줄 바꿈 문자는 플랫폼(Unix, Windows 등)마다 다릅니다. 아래의 분할 스크립트는 모든 플랫폼의 줄 바꿈을 인식합니다.

+ +
let text = 'Some text\nAnd some more\r\nAnd yet\rThis is the end'
+let lines = text.split(/\r\n|\r|\n/)
+console.log(lines) // logs [ 'Some text', 'And some more', 'And yet', 'This is the end' ]
+ +

정규 표현식 패턴의 순서를 바꾸면 작동하지 않을 수 있습니다.

+ +

여러 줄에서 정규 표현식 사용하기

+ +
let s = 'Please yes\nmake my day!'
+
+s.match(/yes.*day/);
+// Returns null
+
+s.match(/yes[^]*day/);
+// Returns ["yes\nmake my day"]
+ +

접착 플래그와 함께 사용하기

+ +

{{JSxRef("Global_Objects/RegExp/sticky", "sticky")}} 플래그는 해당 정규 표현식이 접착 판별, 즉 {{jsxref("RegExp.prototype.lastIndex")}}에서 시작하는 일치만 확인하도록 할 수 있습니다.

+ +
let str = '#foo#'
+let regex = /foo/y
+
+regex.lastIndex = 1
+regex.test(str)      // true
+regex.lastIndex = 5
+regex.test(str)      // false (lastIndex is taken into account with sticky flag)
+regex.lastIndex      // 0 (reset after match failure)
+ +

접착과 전역 플래그의 차이

+ +

접착 플래그 y의 일치는 정확히 lastIndex 위치에서만 발생할 수 있으나, 전역 플래그 g의 경우 lastIndex 또는 그 이후에서도 발생할 수 있습니다.

+ +
re = /\d/y;
+while (r = re.exec("123 456")) console.log(r, "AND re.lastIndex", re.lastIndex);
+
+// [ '1', index: 0, input: '123 456', groups: undefined ] AND re.lastIndex 1
+// [ '2', index: 1, input: '123 456', groups: undefined ] AND re.lastIndex 2
+// [ '3', index: 2, input: '123 456', groups: undefined ] AND re.lastIndex 3
+//   ... and no more match.
+ +

전역 플래그 g를 사용했다면, 3개가 아니고 6개 숫자 모두 일치했을 것입니다.

+ +

정규 표현식과 Unicode 문자

+ +

 \w\Wa부터 z, A부터 Z, 0부터 9 _ 등의 {{glossary("ASCII")}} 문자에만 일치합니다.

+ +

러시아어나 히브리어와 같은 다른 언어의 문자까지 일치하려면 \uhhhh(이때 hhhh는 해당 문자의 16진법 Unicode 값) 문법을 사용하세요. 아래 예제에서는 문자열에서 Unicode 문자를 추출합니다.

+ +
let text = 'Образец text на русском языке'
+let regex = /[\u0400-\u04FF]+/g
+
+let match = regex.exec(text)
+console.log(match[0])        // logs 'Образец'
+console.log(regex.lastIndex) // logs '7'
+
+let match2 = regex.exec(text)
+console.log(match2[0])       // logs 'на' [did not log 'text']
+console.log(regex.lastIndex) // logs '15'
+
+// and so on
+ +

유니코드 속성 이스케이프 기능을 사용해 \p{scx=Cyrl}과 같은 간단한 구문으로 이 문제를 해결할 수 있습니다.

+ +

URL에서 서브도메인 추출하기

+ +
let url = 'http://xxx.domain.com'
+console.log(/[^.]+/.exec(url)[0].substr(7)) // logs 'xxx'
+ +
+

이 때는 정규표현식보단 URL API를 통해 브라우저에 내장된 URL 구문 분석기를 사용하는 것이 좋습니다.

+
+ +

명세

+ + + + + + + + + + +
명세
{{SpecName('ESDraft', '#sec-regexp-regular-expression-objects', 'RegExp')}}
+ +

브라우저 호환성

+ + + +
{{Compat("javascript.builtins.RegExp")}}
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/regexp/n/index.html b/files/ko/web/javascript/reference/global_objects/regexp/n/index.html new file mode 100644 index 0000000000..5b6706cad2 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/regexp/n/index.html @@ -0,0 +1,66 @@ +--- +title: RegExp.$1-$9 +slug: Web/JavaScript/Reference/Global_Objects/RegExp/n +translation_of: Web/JavaScript/Reference/Global_Objects/RegExp/n +--- +
{{JSRef}} {{non-standard_header}}
+ +

비표준 $1, $2, $3, $4, $5, $6, $7, $8, $9 속성들은 정적이며, 괄호로 묶인 하위 문자열 match들을 포함하는 정규 표현식의 읽기 전용 속성들입니다.

+ +

Syntax

+ +
RegExp.$1
+RegExp.$2
+RegExp.$3
+RegExp.$4
+RegExp.$5
+RegExp.$6
+RegExp.$7
+RegExp.$8
+RegExp.$9
+
+ +

Description

+ +

$1, ..., $9 properties are static, they are not a property of an individual regular expression object. Instead, you always use them as RegExp.$1, ..., RegExp.$9.

+ +

The values of these properties are read-only and modified whenever successful matches are made.

+ +

The number of possible parenthesized substrings is unlimited, but the RegExp object can only hold the first nine. You can access all parenthesized substrings through the returned array's indexes.

+ +

These properties can be used in the replacement text for the {{jsxref("String.replace")}} method. When used this way, do not prepend them with RegExp. The example below illustrates this. When parentheses are not included in the regular expression, the script interprets $n's literally (where n is a positive integer).

+ +

Examples

+ +

Using $n with String.replace

+ +

아래의 script는 first last 포맷의 이름과 매치하기 위해 {{jsxref("String")}} 인스턴스의 {{jsxref("String.prototype.replace()", "replace()")}} 메소드를 사용하고 그것을 last, first 포맷으로 출력한다. 대체 텍스트에서, 이 script는 정규 표현식 패턴에서 매칭되는 괄호들에 해당하는 결과들을 나타내는 $1 과 $2 를 사용한다.

+ +
var re = /(\w+)\s(\w+)/;
+var str = 'John Smith';
+str.replace(re, '$2, $1'); // "Smith, John"
+RegExp.$1; // "John"
+RegExp.$2; // "Smith"
+
+ +

Specifications

+ +

Non-standard. Not part of any current specification.

+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.RegExp.n")}}

+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/regexp/regexp/index.html b/files/ko/web/javascript/reference/global_objects/regexp/regexp/index.html new file mode 100644 index 0000000000..387b5bceff --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/regexp/regexp/index.html @@ -0,0 +1,114 @@ +--- +title: RegExp() constructor +slug: Web/JavaScript/Reference/Global_Objects/RegExp/RegExp +tags: + - Constructor + - JavaScript + - Reference + - RegExp +translation_of: Web/JavaScript/Reference/Global_Objects/RegExp/RegExp +--- +
{{JSRef}}
+ +

RegExp 생성자는 패턴을 사용해 텍스트를 판별할 때 사용하는 정규 표현식 객체를 생성합니다.

+ +

정규 표현식에 대한 소개는 JavaScript 안내서의 정규 표현식 장을 참고하세요.

+ +
{{EmbedInteractiveExample("pages/js/regexp-constructor.html")}}
+ + + +

구문

+ +

리터럴, 생성자, 팩토리 표기법이 가능합니다.

+ +
/pattern/flags
+new RegExp(pattern[, flags])
+RegExp(pattern[, flags])
+
+ +

매개변수

+ +
+
pattern
+
정규 표현식을 나타내는 텍스트.
+
ES5부터는, 생성자 표기법에 한정하여 다른 RegExp 객체 혹은 리터럴을 사용할 수 있습니다. 패턴은 특수 문자를 포함할 수 있어서 일반적인 문자열 리터럴보다 더 넓은 범위의 값을 판별할 수 있습니다.
+
flags
+
+

정규 표현식에 추가할 플래그.

+ +

정규 표현식 객체를 패턴으로 제공한 경우 flags 문자열은 제공한 객체의 플래그를 모두 대체하며 lastIndex0으로 초기화합니다. (ES2015 이후)

+ +

flags를 지정하지 않았으면서 정규 표현식 객체를 제공한 경우, 해당 객체의 플래그와 lastIndex를 복제합니다.

+ +

flags는 다음 문자를 조합하여 지정할 수 있습니다.

+ +
+
g (global, 전역 판별)
+
처음 일치에서 중단하지 않고, 문자열 전체를 판별합니다.
+
i (ignore case, 대소문자 무시)
+
u 플래그까지 활성화된 경우, Unicode 대소문자 폴딩을 사용합니다.
+
m (multiline, 여러 줄)
+
시작과 끝 문자(^$)가 여러 줄에 걸쳐 동작합니다. 즉, 전체 입력 문자열의 맨 처음과 맨 끝 뿐만 아니라 (\n이나 \r로 구분되는) 각각의 줄의 처음과 끝도 일치합니다.
+
s ("dotAll")
+
.이 줄 바꿈에도 일치합니다.
+
u (unicode)
+
pattern을 Unicode 코드 포인트 시퀀스로 처리합니다. (이진 문자열 참고)
+
y (sticky, 접착)
+
이 정규 표현식의 lastIndex 속성에 명시된 인덱스에서만 판별하고, 이전/이후 인덱스에서 판별을 시도하지 않습니다.
+
+
+
+ +

예제

+ +

리터럴 표기법과 생성자

+ +

RegExp 객체는 리터럴 표기법과 생성자로써 생성할 수 있습니다.

+ + + +

다음의 세 표현식은 모두 같은 정규 표현식을 생성합니다.

+ +
/ab+c/i
+new RegExp(/ab+c/, 'i') // 리터럴
+new RegExp('ab+c', 'i') // 생성자
+
+ +

리터럴 표기법은 표현식을 평가할 때 정규 표현식을 컴파일합니다. 정규 표현식이 변하지 않으면 리터럴 표기법을 사용하세요. 예를 들어, 반복문 안에서 사용할 정규 표현식을 리터럴 표기법으로 생성하면 정규 표현식을 매번 다시 컴파일하지 않습니다.

+ +

정규 표현식 객체의 생성자(new RegExp('ab+c'))를 사용하면 정규 표현식이 런타임에 컴파일됩니다. 패턴이 변할 가능성이 있거나, 사용자 입력과 같이 알 수 없는 외부 소스에서 가져오는 정규 표현식의 경우 생성자 함수를 사용하세요.

+ +

명세

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-regexp-constructor', 'RegExp constructor')}}
+ +

브라우저 호환성

+ +
+ + +

{{Compat("javascript.builtins.RegExp.RegExp")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/regexp/test/index.html b/files/ko/web/javascript/reference/global_objects/regexp/test/index.html new file mode 100644 index 0000000000..07569e7eaf --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/regexp/test/index.html @@ -0,0 +1,129 @@ +--- +title: RegExp.prototype.test() +slug: Web/JavaScript/Reference/Global_Objects/RegExp/test +tags: + - JavaScript + - Method + - Prototype + - Reference + - RegExp + - 정규 표현식 + - 정규식 +translation_of: Web/JavaScript/Reference/Global_Objects/RegExp/test +--- +
{{JSRef}}
+ +

test() 메서드는 주어진 문자열이 정규 표현식을 만족하는지 판별하고, 그 여부를 true 또는 false로 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/regexp-prototype-test.html", "taller")}}
+ + + +

구문

+ +
regexObj.test(str)
+ +

매개변수

+ +
+
str
+
정규 표현식 일치를 수행할 문자열.
+
+ +

반환 값

+ +

주어진 문자열 str 중 정규 표현식이 일치하는 부분이 있으면 true, 아니면, false.

+ +

설명

+ +

패턴이 문자열 내에 존재하는지에 대한 여부를 알아보고자 할 때 test()를 사용하세요. 일치의 위치 인덱스, 또는 일치하지 않으면 -1을 반환하는 {{jsxref("String.prototype.search()")}}와 달리 test()는 불리언을 반환합니다.

+ +

더 느리지만 더 많은 정보가 필요하면 {{jsxref("RegExp.prototype.exec()", "exec()")}} 메서드를 사용하세요. ({{jsxref("String.prototype.match()")}} 메서드와 비슷합니다.)

+ +

exec()처럼, test()도 전역 탐색 플래그를 제공한 정규 표현식에서 여러 번 호출하면 이전 일치 이후부터 탐색합니다. exec()test()를 혼용해 사용하는 경우에도 해당됩니다.

+ +

예제

+ +

test() 사용하기

+ +

문자열의 맨 처음에 "hello"가 포함됐는지 알아보는 간단한 예제 코드입니다.

+ +
const str = 'hello world!';
+const result = /^hello/.test(str);
+
+console.log(result); // true
+
+ +

다음은 일치 여부에 따라 다른 메시지를 기록하는 예제입니다.

+ +
function testInput(re, str) {
+  let midstring;
+  if (re.test(str)) {
+    midstring = 'contains';
+  } else {
+    midstring = 'does not contain';
+  }
+  console.log(`${str} ${midstring} ${re.source}`);
+}
+
+ +

전역 플래그와 test()

+ +

정규 표현식에 전역 플래그를 설정한 경우, test() 메서드는 정규 표현식의 {{jsxref("RegExp.lastIndex", "lastIndex")}}를 업데이트합니다. ({{jsxref("RegExp.prototype.exec()")}}도 lastIndex 속성을 업데이트합니다.)

+ +

test(str)을 또 호출하면 str 검색을 lastIndex부터 계속 진행합니다. lastIndex 속성은 매 번 test()true를 반환할 때마다 증가하게 됩니다.

+ +
+

참고: test()true를 반환하기만 하면 lastIndex는 초기화되지 않습니다. 심지어 이전과 다른 문자열을 매개변수로 제공해도 그렇습니다!

+
+ +

test()false를 반환할 땐 lastIndex 속성이 0으로 초기화됩니다.

+ +

이 행동에 대한 예제가 다음 코드입니다.

+ +
const regex = /foo/g; // the "global" flag is set
+
+// regex.lastIndex is at 0
+regex.test('foo')     // true
+
+// regex.lastIndex is now at 3
+regex.test('foo')     // false
+
+// regex.lastIndex is at 0
+regex.test('barfoo')  // true
+
+// regex.lastIndex is at 6
+regex.test('foobar')  //false
+
+// regex.lastIndex is at 0
+// (...and so on)
+
+ +

명세

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-regexp.prototype.test', 'RegExp.test')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.RegExp.test")}}

+ +

같이 보기

+ + -- cgit v1.2.3-54-g00ecf