aboutsummaryrefslogtreecommitdiff
path: root/files/ko/web/javascript/reference/global_objects/string/replace/index.html
diff options
context:
space:
mode:
Diffstat (limited to 'files/ko/web/javascript/reference/global_objects/string/replace/index.html')
-rw-r--r--files/ko/web/javascript/reference/global_objects/string/replace/index.html299
1 files changed, 299 insertions, 0 deletions
diff --git a/files/ko/web/javascript/reference/global_objects/string/replace/index.html b/files/ko/web/javascript/reference/global_objects/string/replace/index.html
new file mode 100644
index 0000000000..3b189bfbf5
--- /dev/null
+++ b/files/ko/web/javascript/reference/global_objects/string/replace/index.html
@@ -0,0 +1,299 @@
+---
+title: String.prototype.replace()
+slug: Web/JavaScript/Reference/Global_Objects/String/replace
+translation_of: Web/JavaScript/Reference/Global_Objects/String/replace
+---
+<div>{{JSRef}}</div>
+
+<p><strong><code>replace()</code></strong> 메서드는 어떤 패턴에 일치하는 일부 또는 모든 부분이 교체된 새로운 문자열을 반환합니다. 그 패턴은 문자열이나 정규식({{jsxref("RegExp")}})이 될 수 있으며, 교체 문자열은 문자열이나 모든 매치에 대해서 호출된 함수일 수 있습니다.</p>
+
+<p> </p>
+
+<p>pattern이 문자열 인 경우, 첫 번째 문자열만 치환이 되며 원래 문자열은 변경되지 않습니다.</p>
+
+<p>{{EmbedInteractiveExample("pages/js/string-replace.html")}}</p>
+
+<h2 id="구문">구문</h2>
+
+<pre><code>var newStr = str.replace(regexp|substr, newSubstr|function)</code></pre>
+
+<h3 id="매개변수">매개변수</h3>
+
+<dl>
+ <dt><code>regexp</code> (pattern)</dt>
+ <dd>정규식({{jsxref ( "RegExp")}}) 객체 또는 리터럴. 일치하는 항목은 <code>newSubStr</code> 또는 지정된 함수(<code>function</code>)가 반환 한 값으로 대체됩니다.</dd>
+ <dt><code>substr</code> (pattern)</dt>
+ <dd><code>newSubStr</code>로 대체 될 {{jsxref ( "String")}}. 정규식이 아닌 글자 그대로의 문자열로 처리됩니다. 오직 첫 번째 일치되는 문자열만이 교체됩니다.</dd>
+ <dt><code>newSubStr</code> (replacement)</dt>
+ <dd>첫번째 파라미터를 대신할 문자열({{jsxref("String")}}). 여러가지 대체 패턴들이 지원됩니다. 아래의 "<a href="#Specifying_a_string_as_a_parameter">매개변수가 <code>string</code>으로 지정되었을 때</a>" 섹션을 참고하세요.</dd>
+ <dt><code>function</code> (replacement)</dt>
+ <dd>주어진 <code>regexp</code> 또는 <code>substr</code>에 일치하는 요소를 대체하는 데 사용될 새 하위 문자열을 생성하기 위해 호출되는 함수. 이 함수에 제공되는 인수는 아래 "<a href="#Specifying_a_function_as_a_parameter">매개변수가 <code>function</code>으로 지정되었을 때</a>"단원에서 설명합니다.</dd>
+</dl>
+
+<h3 id="반환값">반환값</h3>
+
+<p>어떤 패턴에 일치하는 일부 또는 모든 부분이 교체된 새로운 문자열</p>
+
+<h2 id="설명">설명</h2>
+
+<p>이 메서드는 호출된 {{jsxref("String")}} 객체를 바꾸지 않습니다. 단순히 새로운 문자열을 리턴합니다.</p>
+
+<p>모든 문자열에 대해 검색하고 바꾸려면 정규표현식의 <code>g</code>플래그를 포함하세요.</p>
+
+<h3 id="매개변수가_string으로_지정되었을_때">매개변수가 <code>string</code>으로 지정되었을 때</h3>
+
+<p><code>replacement</code> 문자열은 다음과 같은 특수 교체 패턴을 포함할 수 있습니다.</p>
+
+<table class="fullwidth-table">
+ <tbody>
+ <tr>
+ <td class="header">Pattern</td>
+ <td class="header">Inserts</td>
+ </tr>
+ <tr>
+ <td><code>$$</code></td>
+ <td> "<code>$</code>" 기호를 삽입합니다.</td>
+ </tr>
+ <tr>
+ <td><code>$&amp;</code></td>
+ <td>매치된 문자열을 삽입합니다.</td>
+ </tr>
+ <tr>
+ <td><code>$`</code></td>
+ <td>매치된 문자열 앞쪽까지의 문자열을 삽입합니다.</td>
+ </tr>
+ <tr>
+ <td><code>$'</code></td>
+ <td>매치된 문자열의 문자열을 삽입합니다.</td>
+ </tr>
+ <tr>
+ <td><code>$<em>n</em></code></td>
+ <td>
+ <p><em><code>n</code></em>이 1이상 99이하의 정수라면, 첫번째 매개변수로 넘겨진 {{jsxref("RegExp")}}객체에서 소괄호로 묶인 <em><code>n</code></em>번째의 부분 표현식으로 매치된 문자열을 삽입합니다.</p>
+ </td>
+ </tr>
+ </tbody>
+</table>
+
+<h3 id="매개변수가_function으로_지정되었을_때">매개변수가 <code>function</code>으로 지정되었을 때</h3>
+
+<p>두번째 매개변수로 함수를 지정할 수 있습니다. 이 경우, 함수는 정규표현식 매치가 수행된 후 호출될 것입니다. 함수의 반환값은 교체될 문자열이 됩니다. (참고: 윗쪽에서 언급된 특수 교체 패턴은 반환값에 <em>적용되지 않습니다.</em>) 만약 정규표현식의 플래그로 글로벌(<code>g</code>)이 오는 경우, 함수는 매치될 때마다 계속 호출될 것입니다. </p>
+
+<p>함수의 매개변수들은 다음과 같습니다.</p>
+
+<table class="fullwidth-table">
+ <tbody>
+ <tr>
+ <td class="header">Possible name</td>
+ <td class="header">Supplied value</td>
+ </tr>
+ <tr>
+ <td><code>match</code></td>
+ <td>매치된 문자열. (윗쪽의 <code>$&amp; </code>표현식으로 매치된 경우와 동일합니다.)</td>
+ </tr>
+ <tr>
+ <td><code>p1,<br>
+ p2,<br>
+ ...</code></td>
+ <td>윗쪽의 $n 표현식과 동일합니다. (<code>$1</code>은 <code>p1</code>, <code>$2</code>는 <code>p2</code>...) 예를 들어, 만약 정규표현식 <code>/(\a+)(\b+)/</code> 이 주어진다면<code><font face="Open Sans, Arial, sans-serif"> </font></code><code>p1</code>은 <code>\a+</code>와 매치되고 <code>p2</code>는 <code>\b+</code>와 매치됩니다.</td>
+ </tr>
+ <tr>
+ <td><code>offset</code></td>
+ <td>조사된 전체 문자열 중에서 매치된 문자열의 <code>index.</code>(예를 들어, 조사될 전체 문자열이 <code>abcd</code>이고, 매치된 문자열이 <code>bc</code>면 이 매개변수의 값은 1이 됩니다.)</td>
+ </tr>
+ <tr>
+ <td><code>string</code></td>
+ <td>조사된 전체 문자열 (<code>replace</code>를 호출한 <code>string</code>)</td>
+ </tr>
+ </tbody>
+</table>
+
+<p>인수의 정확한 수는 첫 번째 인수가 {{jsxref ( "RegExp")}} 객체인지 아닌지에 따라 다르며, 소괄호로 묶이는 부분표현식의 갯수에 따라 달라집니다.</p>
+
+<p> </p>
+
+<p>다음 예제는 <code>newString</code>을 <code>'abc - 12345 - #$*%'</code>로 교체합니다:</p>
+
+<pre><code>function replacer(match, p1, p2, p3, offset, string) {
+ // p1 is nondigits, p2 digits, and p3 non-alphanumerics
+ return [p1, p2, p3].join(' - ');
+}
+var newString = 'abc12345#$*%'.replace(/([^\d]*)(\d*)([^\w]*)/, replacer);
+console.log(newString); // abc - 12345 - #$*%</code></pre>
+
+<h2 id="예제">예제</h2>
+
+<h3 id="replace()의_정규표현식_정의"><code>replace()</code>의 정규표현식 정의</h3>
+
+<p>다음 예제에서, 대소문자를 구분하지 않는 정규표현식을 <code>replace()</code>에 정의했습니다.</p>
+
+<pre class="brush: js">var str = 'Twas the night before Xmas...';
+var newstr = str.replace(/xmas/i, 'Christmas');
+console.log(newstr); // Twas the night before Christmas...
+</pre>
+
+<p>'Twas the night before Christmas...'로 출력됩니다.</p>
+
+<h3 id="global과_ignore를_사용한_replace()"><code>global</code>과 <code>ignore</code>를 사용한 <code>replace()</code></h3>
+
+<p>Global replace는 정규식으로만 수행 할 수 있습니다. 다음 예제에서 정규 표현식은 replace()가 'apples'를 'oranges'로 바꿀 수 있도록 global 및 ignore case 플래그를 포함합니다.</p>
+
+<pre class="brush: js">var re = /apples/gi;
+var str = 'Apples are round, and apples are juicy.';
+var newstr = str.replace(re, 'oranges');
+console.log(newstr); // oranges are round, and oranges are juicy.
+</pre>
+
+<p>'오렌지는 둥글고 오렌지는 맛있습니다.' 가 출력됩니다.</p>
+
+<p> </p>
+
+<h3 id="문자열의_단어_치환">문자열의 단어 치환</h3>
+
+<p>다음 스크립트는 문자열의 단어를 전환합니다. 대체 텍스트의 경우 스크립트는 <code>$1</code> 와 <code>$2</code> 대체 패턴을 사용합니다.</p>
+
+<pre class="brush: js">var re = /(\w+)\s(\w+)/;
+var str = 'John Smith';
+var newstr = str.replace(re, '$2, $1');
+console.log(newstr); // Smith, John
+</pre>
+
+<p>'Smith, John.'이 출력됩니다.</p>
+
+<h3 id="Using_an_inline_function_that_modifies_the_matched_characters">Using an inline function that modifies the matched characters</h3>
+
+<p> </p>
+
+<p>이 예제에서 문자열의 대문자가 모두 소문자로 변환되고 일치되는 위치 바로 앞에 하이픈이 삽입됩니다. 여기에서 중요한 점은 일치되는 항목이 대체 항목으로 다시 반환되기 전에 추가 작업이 필요하다는 것입니다.</p>
+
+<p>바꾸기 기능은 일치하는 스니펫을 매개 변수로 받고 이를 사용하여 각 케이스별로 변환한후 반환하기 전에 하이픈을 연결합니다.</p>
+
+<p> </p>
+
+<pre class="brush: js">function styleHyphenFormat(propertyName) {
+ function upperToHyphenLower(match) {
+ return '-' + match.toLowerCase();
+ }
+ return propertyName.replace(/[A-Z]/g, upperToHyphenLower);
+}
+</pre>
+
+<p>Given <code>styleHyphenFormat('borderTop')</code>, this returns 'border-top'.</p>
+
+<p>Because we want to further transform the <em>result</em> of the match before the final substitution is made, we must use a function. This forces the evaluation of the match prior to the {{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}} method. If we had tried to do this using the match without a function, the {{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}} would have no effect.</p>
+
+<pre class="brush: js">var newString = propertyName.replace(/[A-Z]/g, '-' + '$&amp;'.toLowerCase()); // won't work
+</pre>
+
+<p>This is because <code>'$&amp;'.toLowerCase()</code> would be evaluated first as a string literal (resulting in the same <code>'$&amp;'</code>) before using the characters as a pattern.</p>
+
+<h3 id="Replacing_a_Fahrenheit_degree_with_its_Celsius_equivalent">Replacing a Fahrenheit degree with its Celsius equivalent</h3>
+
+<p>The following example replaces a Fahrenheit degree with its equivalent Celsius degree. The Fahrenheit degree should be a number ending with F. The function returns the Celsius number ending with C. For example, if the input number is 212F, the function returns 100C. If the number is 0F, the function returns -17.77777777777778C.</p>
+
+<p>The regular expression <code>test</code> checks for any number that ends with F. The number of Fahrenheit degree is accessible to the function through its second parameter, <code>p1</code>. The function sets the Celsius number based on the Fahrenheit degree passed in a string to the <code>f2c()</code> function. <code>f2c()</code> then returns the Celsius number. This function approximates Perl's <code>s///e</code> flag.</p>
+
+<pre class="brush: js">function f2c(x) {
+ function convert(str, p1, offset, s) {
+ return ((p1 - 32) * 5/9) + 'C';
+ }
+ var s = String(x);
+ var test = /(-?\d+(?:\.\d*)?)F\b/g;
+ return s.replace(test, convert);
+}
+</pre>
+
+<h3 id="Use_an_inline_function_with_a_regular_expression_to_avoid_for_loops">Use an inline function with a regular expression to avoid <code>for</code> loops</h3>
+
+<p>The following example takes a string pattern and converts it into an array of objects.</p>
+
+<p><strong>Input:</strong></p>
+
+<p>A string made out of the characters <code>x</code>, <code>-</code> and <code>_</code></p>
+
+<pre>x-x_
+x---x---x---x---
+x-xxx-xx-x-
+x_x_x___x___x___
+</pre>
+
+<p><strong>Output:</strong></p>
+
+<p>An array of objects. An <code>'x'</code> denotes an <code>'on'</code> state, a <code>'-'</code> (hyphen) denotes an <code>'off'</code> state and an <code>'_'</code> (underscore) denotes the length of an <code>'on'</code> state.</p>
+
+<pre class="brush: json">[
+ { on: true, length: 1 },
+ { on: false, length: 1 },
+ { on: true, length: 2 }
+ ...
+]
+</pre>
+
+<p><strong>Snippet:</strong></p>
+
+<pre class="brush: js">var str = 'x-x_';
+var retArr = [];
+str.replace(/(x_*)|(-)/g, function(match, p1, p2) {
+ if (p1) { retArr.push({ on: true, length: p1.length }); }
+ if (p2) { retArr.push({ on: false, length: 1 }); }
+});
+
+console.log(retArr);
+</pre>
+
+<p>This snippet generates an array of 3 objects in the desired format without using a <code>for</code> loop.</p>
+
+<h2 id="명세">명세</h2>
+
+<table class="standard-table">
+ <tbody>
+ <tr>
+ <th scope="col">Specification</th>
+ <th scope="col">Status</th>
+ <th scope="col">Comment</th>
+ </tr>
+ <tr>
+ <td>{{SpecName('ES3')}}</td>
+ <td>{{Spec2('ES3')}}</td>
+ <td>Initial definition. Implemented in JavaScript 1.2.</td>
+ </tr>
+ <tr>
+ <td>{{SpecName('ES5.1', '#sec-15.5.4.11', 'String.prototype.replace')}}</td>
+ <td>{{Spec2('ES5.1')}}</td>
+ <td> </td>
+ </tr>
+ <tr>
+ <td>{{SpecName('ES6', '#sec-string.prototype.replace', 'String.prototype.replace')}}</td>
+ <td>{{Spec2('ES6')}}</td>
+ <td> </td>
+ </tr>
+ <tr>
+ <td>{{SpecName('ESDraft', '#sec-string.prototype.replace', 'String.prototype.replace')}}</td>
+ <td>{{Spec2('ESDraft')}}</td>
+ <td> </td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="브라우저_호환성">브라우저 호환성</h2>
+
+<div> </div>
+
+<div id="compat-mobile">{{Compat("javascript.builtins.String.replace")}}</div>
+
+<h2 id="Firefox-specific_notes">Firefox-specific notes</h2>
+
+<ul>
+ <li>Starting with Gecko 27 {{geckoRelease(27)}}, this method has been adjusted to conform with the ECMAScript specification. When <code>replace()</code> is called with a global regular expression, the {{jsxref("RegExp.lastIndex")}} property (if specified) will be reset to <code>0</code> ({{bug(501739)}}).</li>
+ <li>Starting with Gecko 39 {{geckoRelease(39)}}, the non-standard <code>flags</code> argument is deprecated and throws a console warning ({{bug(1142351)}}).</li>
+ <li>Starting with Gecko 47 {{geckoRelease(47)}}, the non-standard <code>flags</code> argument is no longer supported in non-release builds and will soon be removed entirely ({{bug(1245801)}}).</li>
+ <li>Starting with Gecko 49 {{geckoRelease(49)}}, the non-standard <code>flags</code> argument is no longer supported ({{bug(1108382)}}).</li>
+</ul>
+
+<h2 id="같이_보기">같이 보기</h2>
+
+<ul>
+ <li>{{jsxref("String.prototype.match()")}}</li>
+ <li>{{jsxref("RegExp.prototype.exec()")}}</li>
+ <li>{{jsxref("RegExp.prototype.test()")}}</li>
+</ul>