diff options
Diffstat (limited to 'files/ko/web/javascript/reference/global_objects/string')
30 files changed, 4211 insertions, 0 deletions
diff --git a/files/ko/web/javascript/reference/global_objects/string/charat/index.html b/files/ko/web/javascript/reference/global_objects/string/charat/index.html new file mode 100644 index 0000000000..a5a68c03be --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/charat/index.html @@ -0,0 +1,260 @@ +--- +title: String.prototype.charAt() +slug: Web/JavaScript/Reference/Global_Objects/String/charAt +tags: + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/charAt +--- +<div>{{JSRef}}</div> + +<p><strong>charAt() </strong>함수는 문자열에서 특정 인덱스에 위치하는 유니코드 단일문자를 반환합니다. </p> + +<div>{{EmbedInteractiveExample("pages/js/string-charat.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>str</var>.charAt(<var>index</var>)</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<ul> + <li>0과 문자열의 길이 - 1 사이의 정수값. </li> + <li>인자를 생략하면 기본값으로 0를 설정되고 첫 문자를 반환한다. </li> +</ul> + +<dl> + <dt><code>index</code></dt> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<ul> + <li>지정된 인덱스에 해당하는 유니코드 단일문자를 반환한다.</li> + <li>만약 인덱스가 문자열 길이보다 큰 경우 빈 문자열 (예) " " 을 반환한다. </li> +</ul> + +<h2 id="설명">설명</h2> + +<p>문자열 내의 문자는 왼쪽에서 오른쪽으로 순번(인덱스)이 매겨집니다. 첫 번째 문자의 순번은 0, 그리고 <code>stringName</code> 이라는 이름을 가진 문자열의 마지막 문자 순번은 <code>stringName.length - 1 </code>입니다. <code>index</code>가 문자열 길이를 벗어나면 빈 문자열을 반환하게 됩니다.</p> + +<p><code>index</code>를 제공하지 않으면 기본값은 0입니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="문자열_내의_다른_위치에_있는_문자들을_출력하기">문자열 내의 다른 위치에 있는 문자들을 출력하기</h3> + +<p>아래 예제는 문자열 <code>"Brave new world"</code>의 다른 위치에 있는 문자들을 출력합니다.</p> + +<pre class="brush: js">var anyString = 'Brave new world'; +console.log("The character at index 0 is '" + anyString.charAt() + "'"); +// No index was provided, used 0 as default + +console.log("The character at index 0 is '" + anyString.charAt(0) + "'"); +console.log("The character at index 1 is '" + anyString.charAt(1) + "'"); +console.log("The character at index 2 is '" + anyString.charAt(2) + "'"); +console.log("The character at index 3 is '" + anyString.charAt(3) + "'"); +console.log("The character at index 4 is '" + anyString.charAt(4) + "'"); +console.log("The character at index 999 is '" + anyString.charAt(999) + "'"); +</pre> + +<p>프로그램의 실행 결과는 아래와 같습니다.</p> + +<pre class="brush: js">The character at index 0 is 'B' +The character at index 1 is 'r' +The character at index 2 is 'a' +The character at index 3 is 'v' +The character at index 4 is 'e' +The character at index 999 is '' +</pre> + +<h3 id="문자열_내의_모든_문자_얻기">문자열 내의 모든 문자 얻기</h3> + +<p>아래 예제는 문자열 전체를 순회하며 각 문자가 완전한지 확인하는 프로그램입니다. 심지어 <a href="https://ko.wikipedia.org/wiki/%EC%9C%A0%EB%8B%88%EC%BD%94%EB%93%9C_%ED%8F%89%EB%A9%B4">기본 다국어 평면(Basic Multilingual Plane)</a>에 포함되지 않은 문자들이 포함되어 있다고 하더라도 잘 동작합니다. </p> + +<pre class="brush: js">var str = 'A \uD87E\uDC04 Z'; // 기본 다국어 평면에 포함되지 않는 문자를 사용합니다. +for (var i = 0, chr; i < str.length; i++) { + if ((chr = getWholeChar(str, i)) === false) { + continue; + } + // Adapt this line at the top of each loop, passing in the whole string and + // the current iteration and returning a variable to represent the + // individual character + + console.log(chr); +} + +function getWholeChar(str, i) { + var code = str.charCodeAt(i); + + if (Number.isNaN(code)) { + return ''; // Position not found + } + if (code < 0xD800 || code > 0xDFFF) { + return str.charAt(i); + } + + // High surrogate (could change last hex to 0xDB7F to treat high private + // surrogates as single characters) + if (0xD800 <= code && code <= 0xDBFF) { + if (str.length <= (i + 1)) { + throw 'High surrogate without following low surrogate'; + } + var next = str.charCodeAt(i + 1); + if (0xDC00 > next || next > 0xDFFF) { + throw 'High surrogate without following low surrogate'; + } + return str.charAt(i) + str.charAt(i + 1); + } + // Low surrogate (0xDC00 <= code && code <= 0xDFFF) + if (i === 0) { + throw 'Low surrogate without preceding high surrogate'; + } + var prev = str.charCodeAt(i - 1); + + // (could change last hex to 0xDB7F to treat high private + // surrogates as single characters) + if (0xD800 > prev || prev > 0xDBFF) { + throw 'Low surrogate without preceding high surrogate'; + } + // We can pass over low surrogates now as the second component + // in a pair which we have already processed + return false; +} +</pre> + +<p><a href="/ko/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">비구조화 할당</a>을 허용하는 ECMAScript 2016 환경에서는 아래 예제 코드가 더 간결하고, 문자가 <a href="https://ko.wikipedia.org/wiki/UTF-16">서러게이트 페어</a>가 되는 것을 허용할 때는 증가해야 하는 변수를 자동적으로 증가하기에 위의 코드보다 다소 더 유연합니다.</p> + +<pre class="brush: js">var str = 'A\uD87E\uDC04Z'; // We could also use a non-BMP character directly +for (var i = 0, chr; i < str.length; i++) { + [chr, i] = getWholeCharAndI(str, i); + // Adapt this line at the top of each loop, passing in the whole string and + // the current iteration and returning an array with the individual character + // and 'i' value (only changed if a surrogate pair) + + console.log(chr); +} + +function getWholeCharAndI(str, i) { + var code = str.charCodeAt(i); + + if (Number.isNaN(code)) { + return ''; // Position not found + } + if (code < 0xD800 || code > 0xDFFF) { + return [str.charAt(i), i]; // Normal character, keeping 'i' the same + } + + // High surrogate (could change last hex to 0xDB7F to treat high private + // surrogates as single characters) + if (0xD800 <= code && code <= 0xDBFF) { + if (str.length <= (i + 1)) { + throw 'High surrogate without following low surrogate'; + } + var next = str.charCodeAt(i + 1); + if (0xDC00 > next || next > 0xDFFF) { + throw 'High surrogate without following low surrogate'; + } + return [str.charAt(i) + str.charAt(i + 1), i + 1]; + } + // Low surrogate (0xDC00 <= code && code <= 0xDFFF) + if (i === 0) { + throw 'Low surrogate without preceding high surrogate'; + } + var prev = str.charCodeAt(i - 1); + + // (could change last hex to 0xDB7F to treat high private surrogates + // as single characters) + if (0xD800 > prev || prev > 0xDBFF) { + throw 'Low surrogate without preceding high surrogate'; + } + // Return the next character instead (and increment) + return [str.charAt(i + 1), i + 1]; +} +</pre> + +<h3 id="기본다국어평면(Basic-Multilingual-Plane)이_아닌_문자들을_지원하도록_charAt()_수정하기">기본다국어평면(Basic-Multilingual-Plane)이 아닌 문자들을 지원하도록 <code>charAt()</code> 수정하기</h3> + +<p>어떠한 non-BMP 문자들이 나타났는지 호출자가 알 필요가 없기 때문에 non-BMP 문자들을 지원하도록 하는데는 앞의 예제들이 더 자주 사용되지만, 인덱스로 문자를 선택하는데 있어서 문자열 내에 서로게이트 페어들이 하나의 문자들로 처리되길 원한다면, 아래 예제 코드를 사용하면 됩니다.</p> + +<pre class="brush: js">function fixedCharAt(str, idx) { + var ret = ''; + str += ''; + var end = str.length; + + var surrogatePairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; + while ((surrogatePairs.exec(str)) != null) { + var li = surrogatePairs.lastIndex; + if (li - 2 < idx) { + idx++; + } else { + break; + } + } + + if (idx >= end || idx < 0) { + return ''; + } + + ret += str.charAt(idx); + + if (/[\uD800-\uDBFF]/.test(ret) && /[\uDC00-\uDFFF]/.test(str.charAt(idx + 1))) { + // Go one further, since one of the "characters" is part of a surrogate pair + ret += str.charAt(idx + 1); + } + return ret; +} +</pre> + +<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('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.4', 'String.prototype.charAt')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.charat', 'String.prototype.charAt')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.charat', 'String.prototype.charAt')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.builtins.String.charAt")}}</p> + +<h2 id="관련문서">관련문서</h2> + +<ul> + <li>{{jsxref("String.prototype.indexOf()")}}</li> + <li>{{jsxref("String.prototype.lastIndexOf()")}}</li> + <li>{{jsxref("String.prototype.charCodeAt()")}}</li> + <li>{{jsxref("String.prototype.codePointAt()")}}</li> + <li>{{jsxref("String.prototype.split()")}}</li> + <li>{{jsxref("String.fromCodePoint()")}}</li> + <li><a href="https://mathiasbynens.be/notes/javascript-unicode">JavaScript has a Unicode problem – Mathias Bynens</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/charcodeat/index.html b/files/ko/web/javascript/reference/global_objects/string/charcodeat/index.html new file mode 100644 index 0000000000..9777130911 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/charcodeat/index.html @@ -0,0 +1,169 @@ +--- +title: String.prototype.charCodeAt() +slug: Web/JavaScript/Reference/Global_Objects/String/charCodeAt +tags: + - JavaScript + - Method + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/charCodeAt +--- +<div>{{JSRef}}</div> + +<p><strong><code>charCodeAt()</code></strong> 메서드는 주어진 인덱스에 대한 UTF-16 코드를 나타내는 0부터 65535 사이의 정수를 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/string-charcodeat.html")}}</div> + + + +<p>전체 코드 값을 원하신다면 {{jsxref("String.prototype.codePointAt()")}}을 사용하세요.</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>str</var>.charCodeAt(<var>index</var>)</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>index</code></dt> + <dd>0 이상이고 문자열의 길이보다 작은 정수. 숫자가 아니라면 0을 기본값으로 사용함. </dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 인덱스 대한 문자에 대한 UTF-16 코드를 나타내는 숫자<br> + 범위 밖으로 넘어갔을 경우 {{jsxref("Global_Objects/NaN", "NaN")}}</p> + +<h2 id="설명">설명</h2> + +<p>Unicode code points range from 0 to 1114111 (0x10FFFF). The first 128 Unicode code points are a direct match of the ASCII character encoding. For information on Unicode, see the <a href="/en-US/docs/Web/JavaScript/Guide/Values,_variables,_and_literals#Unicode">JavaScript Guide</a>.</p> + +<p>Note that <code>charCodeAt()</code> will always return a value that is less than 65536. This is because the higher code points are represented by a pair of (lower valued) "surrogate" pseudo-characters which are used to comprise the real character. Because of this, in order to examine or reproduce the full character for individual characters of value 65536 and above, for such characters, it is necessary to retrieve not only <code>charCodeAt(i)</code>, but also <code>charCodeAt(i+1)</code> (as if examining/reproducing a string with two letters), or to use codePointAt(i) instead. See example 2 and 3 below.</p> + +<p><code>charCodeAt()</code> returns {{jsxref("Global_Objects/NaN", "NaN")}} if the given index is less than 0 or is equal to or greater than the length of the string.</p> + +<p>Backward compatibilty: In historic versions (like JavaScript 1.2) the <code>charCodeAt()</code> method returns a number indicating the ISO-Latin-1 codeset value of the character at the given index. The ISO-Latin-1 codeset ranges from 0 to 255. The first 0 to 127 are a direct match of the ASCII character set.</p> + +<h2 id="예제">예제</h2> + +<h3 id="Using_charCodeAt()">Using <code>charCodeAt()</code></h3> + +<p>The following example returns 65, the Unicode value for A.</p> + +<pre class="brush: js">'ABC'.charCodeAt(0); // returns 65 +</pre> + +<h3 id="Fixing_charCodeAt()_to_handle_non-Basic-Multilingual-Plane_characters_if_their_presence_earlier_in_the_string_is_unknown">Fixing <code>charCodeAt()</code> to handle non-Basic-Multilingual-Plane characters if their presence earlier in the string is unknown</h3> + +<p>This version might be used in for loops and the like when it is unknown whether non-BMP characters exist before the specified index position.</p> + +<pre class="brush: js">function fixedCharCodeAt(str, idx) { + // ex. fixedCharCodeAt('\uD800\uDC00', 0); // 65536 + // ex. fixedCharCodeAt('\uD800\uDC00', 1); // false + idx = idx || 0; + var code = str.charCodeAt(idx); + var hi, low; + + // High surrogate (could change last hex to 0xDB7F to treat high + // private surrogates as single characters) + if (0xD800 <= code && code <= 0xDBFF) { + hi = code; + low = str.charCodeAt(idx + 1); + if (isNaN(low)) { + throw 'High surrogate not followed by low surrogate in fixedCharCodeAt()'; + } + return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000; + } + if (0xDC00 <= code && code <= 0xDFFF) { // Low surrogate + // We return false to allow loops to skip this iteration since should have + // already handled high surrogate above in the previous iteration + return false; + /*hi = str.charCodeAt(idx - 1); + low = code; + return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;*/ + } + return code; +} +</pre> + +<h3 id="Fixing_charCodeAt()_to_handle_non-Basic-Multilingual-Plane_characters_if_their_presence_earlier_in_the_string_is_known">Fixing <code>charCodeAt()</code> to handle non-Basic-Multilingual-Plane characters if their presence earlier in the string is known</h3> + +<pre class="brush: js">function knownCharCodeAt(str, idx) { + str += ''; + var code, + end = str.length; + + var surrogatePairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; + while ((surrogatePairs.exec(str)) != null) { + var li = surrogatePairs.lastIndex; + if (li - 2 < idx) { + idx++; + } + else { + break; + } + } + + if (idx >= end || idx < 0) { + return NaN; + } + + code = str.charCodeAt(idx); + + var hi, low; + if (0xD800 <= code && code <= 0xDBFF) { + hi = code; + low = str.charCodeAt(idx + 1); + // Go one further, since one of the "characters" is part of a surrogate pair + return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000; + } + return code; +} +</pre> + +<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('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.5', 'String.prototype.charCodeAt')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.charcodeat', 'String.prototype.charCodeAt')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.charcodeat', 'String.prototype.charCodeAt')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</div> + +<p>{{Compat("javascript.builtins.String.charCodeAt")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("String.fromCharCode()")}}</li> + <li>{{jsxref("String.prototype.charAt()")}}</li> + <li>{{jsxref("String.fromCodePoint()")}}</li> + <li>{{jsxref("String.prototype.codePointAt()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/concat/index.html b/files/ko/web/javascript/reference/global_objects/string/concat/index.html new file mode 100644 index 0000000000..1d5b4f2cd6 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/concat/index.html @@ -0,0 +1,105 @@ +--- +title: String.prototype.concat() +slug: Web/JavaScript/Reference/Global_Objects/String/concat +tags: + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/concat +--- +<div>{{JSRef}}</div> + +<p><strong><code>concat()</code></strong> 메서드는 매개변수로 전달된 모든 문자열을 호출 문자열에 붙인 새로운 문자열을 반환합니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/string-concat.html")}}</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>str</var>.concat(<var>string2</var>, <var>string3</var>[, ..., <var>stringN</var>])</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>string2...string<em>N</em></code></dt> + <dd>합칠 문자열.</dd> +</dl> + +<h3 id="반환값">반환값</h3> + +<p>주어진 문자열을 모두 붙인 새로운 문자열.</p> + +<h2 id="설명">설명</h2> + +<p><code>concat()</code> 함수는 호출 문자열에 문자열 인수를 이어 붙인 결과를 반환합니다. 원본 문자열과 결과 문자열의 변형은 서로에게 영향을 미치지 않습니다. 인수가 문자열이 아니면 계산 전에 문자열로 변환합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="concat_사용하기"><code>concat()</code> 사용하기</h3> + +<p>아래 예제에서는 문자열을 결합하여 새로운 문자열을 만듭니다.</p> + +<pre><code>var hello = 'Hello, '; +console.log(hello.concat('Kevin', '. Have a nice day.')); +/* Hello, Kevin. Have a nice day. */ + +var greetList = ['Hello', ' ', 'Venkat', '!']; +"".concat(...greetList); // "Hello Venkat!" + +"".concat({}); // [object Object] +"".concat([]); // "" +"".concat(null); // "null" +"".concat(true); // "true" +"".concat(4, 5); // "45"</code></pre> + +<h2 id="성능">성능</h2> + +<p><code>concat()</code> 메서드보다 {{jsxref("Operators/Assignment_Operators", "할당 연산자", "", 1)}} (<code>+</code>, <code>+=</code>)를 사용하는게 더 좋습니다. <a href="https://web.archive.org/web/20170404182053/https://jsperf.com/concat-vs-plus-vs-join">성능 테스트</a> 결과에 따르면 할당 연산자의 속도가 몇 배 빠릅니다.</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.6', 'String.prototype.concat')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.concat', 'String.prototype.concat')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.concat', 'String.prototype.concat')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("javascript.builtins.String.concat")}}</p> + +<div></div> + +<div id="compat-mobile"></div> + +<h2 id="관련문서">관련문서</h2> + +<ul> + <li>{{jsxref("Array.prototype.concat()")}}</li> + <li>{{jsxref("Operators/Assignment_Operators", "Assignment operators", "", 1)}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/endswith/index.html b/files/ko/web/javascript/reference/global_objects/string/endswith/index.html new file mode 100644 index 0000000000..d78645e9f3 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/endswith/index.html @@ -0,0 +1,142 @@ +--- +title: String.prototype.endsWith() +slug: Web/JavaScript/Reference/Global_Objects/String/endsWith +translation_of: Web/JavaScript/Reference/Global_Objects/String/endsWith +--- +<div>{{JSRef}}</div> + +<p>The <strong><code>endsWith()</code></strong> 메서드를 사용하여 어떤 문자열에서 특정 문자열로 끝나는지를 확인할 수 있으며, 그 결과를 <code>true</code> 혹은 <code>false</code>로 반환한다. </p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox"><var>str</var>.endsWith(<var>searchString</var>[, <var>length</var>])</pre> + +<h3 id="파라미터들">파라미터들</h3> + +<dl> + <dt><code>searchString</code></dt> + <dd>이 문자열의 끝이 특정 문자열로 끝나는지를 찾기 원하는 문자열입니다.</dd> + <dt><code>length</code></dt> + <dd>옵션입니다. 찾고자 하는 문자열의 길이값이며, 기본값은 문자열 전체 길이입니다. 문자열의 길이값은 문자열 전체 길이 안에서만 존재하여야 합니다.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>문자열의 끝이 주어진 문자열로 끝나면 <strong><code>true</code></strong>, 그렇지 않다면 <strong><code>false</code></strong></p> + +<h2 id="설명">설명</h2> + +<p>여러분은 이 메서드를 사용하여 어떤 문자열이 특정 문자열로 끝나는지를 확인할 수 있습니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="endsWith_사용하기"><code>endsWith()</code> 사용하기</h3> + +<pre class="brush: js">var str = 'To be, or not to be, that is the question.'; + +console.log(str.endsWith('question.')); // true +console.log(str.endsWith('to be')); // false +console.log(str.endsWith('to be', 19)); // true +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>이 메서드는 ECMAScript 6 규격에 포함되었습니다만 아직까지는 모든 JavaScrpt가 이 기능을 지원하고 있지는 않습니다. 하지만 여러분은 <code>String.prototype.endsWith()</code> 메서드를 다음과 같이 쉽게 <a href="https://en.wikipedia.org/wiki/Polyfill">polyfill</a> 할 수 있습니다:</p> + +<pre class="brush: js">if (!String.prototype.endsWith) { + String.prototype.endsWith = function(searchString, position) { + var subjectString = this.toString(); + if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) { + position = subjectString.length; + } + position -= searchString.length; + var lastIndex = subjectString.indexOf(searchString, position); + return lastIndex !== -1 && lastIndex === position; + }; +} +</pre> + +<h2 id="Specifications">Specifications</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('ES6', '#sec-string.prototype.endswith', 'String.prototype.endsWith')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.endswith', 'String.prototype.endsWith')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Edge</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome("41")}}</td> + <td>{{CompatGeckoDesktop("17")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatSafari("9")}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome("36")}}</td> + <td>{{CompatGeckoMobile("17")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="관련문서">관련문서</h2> + +<ul> + <li>{{jsxref("String.prototype.startsWith()")}}</li> + <li>{{jsxref("String.prototype.includes()")}}</li> + <li>{{jsxref("String.prototype.indexOf()")}}</li> + <li>{{jsxref("String.prototype.lastIndexOf()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/fromcharcode/index.html b/files/ko/web/javascript/reference/global_objects/string/fromcharcode/index.html new file mode 100644 index 0000000000..98b1627666 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/fromcharcode/index.html @@ -0,0 +1,101 @@ +--- +title: String.fromCharCode() +slug: Web/JavaScript/Reference/Global_Objects/String/fromCharCode +tags: + - JavaScript + - Method + - Reference + - String + - Unicode +translation_of: Web/JavaScript/Reference/Global_Objects/String/fromCharCode +--- +<div>{{JSRef}}</div> + +<p><strong><code>String.fromCharCode()</code></strong> 메서드는 UTF-16 코드 유닛의 시퀀스로부터 문자열을 생성해 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/string-fromcharcode.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code>String.fromCharCode(<var>num1</var>[, ...[, <var>numN</var>]])</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>num1, ..., num<em>N</em></code></dt> + <dd>UTF-16 코드 유닛인 숫자 뭉치. 가능한 값의 범위는 0부터 65535(0xFFFF)까지입니다. 0xFFFF를 초과하는 값은 잘립니다. 유효성 검사는 하지 않습니다.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 UTF-16 코드 유닛 N개로 이루어진 문자열.</p> + +<h2 id="설명">설명</h2> + +<p>이 메서드는 {{jsxref("String")}} 객체가 아닌 문자열을 반환합니다.</p> + +<p><code>fromCharCode()</code>는 {{jsxref("String")}}의 정적 메서드이기 때문에 <code>String.fromCharCode()</code>로 사용해야 합니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="fromCharCode()_사용하기"><code>fromCharCode()</code> 사용하기</h3> + +<p>다음 예제는 문자열 <code>"ABC"</code>를 반환합니다..</p> + +<pre class="brush: js">String.fromCharCode(65, 66, 67); // "ABC" +String.fromCharCode(0x2014) // "—" +String.fromCharCode(0x12014) // 숫자 '1'은 무시해서 "—" +</pre> + +<h2 id="더_큰_값과_사용하기">더 큰 값과 사용하기</h2> + +<p>초기 JavaScript 표준화 과정에서 예상했던 것처럼, 대부분의 흔한 유니코드 값을 16비트 숫자로 표현할 수 있고, <code>fromCharCode()</code>가 많은 흔한 값에서 하나의 문자를 반환할 수 있지만, <strong>모든</strong> 유효한 유니코드 값(최대 21비트)을 처리하려면 <code>fromCharCode()</code>만으로는 부족합니다. 높은 코드 포인트의 문자는 써로게이트<sup>surrogate</sup> 값 두 개를 합쳐 하나의 문자를 표현하므로,{{jsxref("String.fromCodePoint()")}}(ES2015 표준) 메서드는 그러한 쌍을 높은 값의 문자로 변환할 수 있습니다.</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('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.3.2', 'StringfromCharCode')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.fromcharcodes', 'String.fromCharCode')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.fromcharcodes', 'String.fromCharCode')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.String.fromCharCode")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("String.fromCodePoint()")}}</li> + <li>{{jsxref("String.prototype.charAt()")}}</li> + <li>{{jsxref("String.prototype.charCodeAt()")}}</li> + <li>{{jsxref("String.prototype.codePointAt()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/includes/index.html b/files/ko/web/javascript/reference/global_objects/string/includes/index.html new file mode 100644 index 0000000000..a3eb79ad16 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/includes/index.html @@ -0,0 +1,125 @@ +--- +title: String.prototype.includes() +slug: Web/JavaScript/Reference/Global_Objects/String/includes +tags: + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/includes +--- +<div>{{JSRef}}</div> + +<p><strong><code>includes()</code></strong> 메서드는 하나의 문자열이 다른 문자열에 포함되어 있는지를 판별하고, 결과를 <code>true</code> 또는 <code>false</code> 로 반환합니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/string-includes.html")}}</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>str</var>.includes(<var>searchString</var>[, <var>position</var>])</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>searchString</code></dt> + <dd>이 문자열에서 찾을 다른 문자열.</dd> + <dt><code>position</code> {{optional_inline}}</dt> + <dd><code>searchString</code>을 찾기 시작할 위치. 기본값 0.</dd> +</dl> + +<h3 id="반환값">반환값</h3> + +<p>문자열을 찾아내면 <code>true</code>. 실패하면 <code>false</code>.</p> + +<h2 id="설명">설명</h2> + +<p><code>includes()</code> 메서드를 사용해 문자열 내에 찾고자 하는 다른 문자열이 있는지 확인할 수 있습니다.</p> + +<h3 id="대소문자_구분">대소문자 구분</h3> + +<p><code>includes()</code> 메서드는 대소문자를 구별합니다. 예를 들어 아래 코드는 <code>false</code>를 반환합니다.</p> + +<pre class="brush: js">'Blue Whale'.includes('blue'); // returns false +</pre> + +<h2 id="예제">예제</h2> + +<h3 id="includes()_사용하기"><code>includes()</code> 사용하기</h3> + +<pre class="brush: js">var str = 'To be, or not to be, that is the question.'; + +console.log(str.includes('To be')); // true +console.log(str.includes('question')); // true +console.log(str.includes('nonexistent')); // false +console.log(str.includes('To be', 1)); // false +console.log(str.includes('TO BE')); // false +</pre> + +<h2 id="폴리필">폴리필</h2> + +<p>이 메서드는 ECMAScript 6 규격에 포함되었습니다만 아직까지는 모든 JavaScrpt가 이 기능을 지원하고 있지는 않습니다. 하지만 여러분은 이 메서드를 다음과 같이 쉽게 <a href="https://en.wikipedia.org/wiki/Polyfill">polyfill</a> 할 수 있습니다.</p> + +<pre class="brush: js">if (!String.prototype.includes) { + String.prototype.includes = function(search, start) { + 'use strict'; + if (typeof start !== 'number') { + start = 0; + } + + if (start + search.length > this.length) { + return false; + } else { + return this.indexOf(search, start) !== -1; + } + }; +} + +</pre> + +<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('ES6', '#sec-string.prototype.includes', 'String.prototype.includes')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.includes', 'String.prototype.includes')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{Compat("javascript.builtins.String.includes")}}</div> + +<h2 id="String.prototype.contains">String.prototype.contains</h2> + +<p>Firefox 18 - 39에서, <code>include()</code> 메서드의 이름은 <code>contains()</code>이었습니다. contains() 함수는 아래와 같은 이유로 {{bug(1102219)}}에서 <code>includes()</code>로 변경되었습니다:</p> + +<p>It's been <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=789036">reported</a> that some websites using MooTools 1.2 broke on Firefox 17. This version of MooTools checks whether <code>String.prototype.contains()</code> exists and, if it doesn't, MooTools adds its own function. With the introduction of this function in Firefox 17, the behavior of that check changed in a way that causes code based on MooTools' <code>String.prototype.contains()</code> implementation to break. As a result, the implementation was <a href="https://hg.mozilla.org/releases/mozilla-aurora/rev/086db97198a8">disabled</a> in Firefox 17 and <code>String.prototype.contains()</code> was available one version later, in Firefox 18, when <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=789036#c32">outreach to MooTools </a>was leading to the <a href="http://mootools.net/blog/2013/02/19/mootools-1-2-6-released">release of MooTools version 1.2.6</a>.</p> + +<p>MooTools 1.3 forces its own version of <code>String.prototype.contains()</code>, so websites relying on it should not break. However, you should note that <a href="http://mootools.net/core/docs/1.3.2/Types/String#String-method:-contains">MooTools 1.3 signature</a> and ECMAScript 6 signatures for this method differ (on the second argument). Later, <a href="https://github.com/mootools/mootools-core/blob/master/Docs/Types/String.md#note">MooTools 1.5+ changed the signature to match the ES6 standard.</a></p> + +<p>Firefox 48에서, <code>String.prototype.contains()</code>은 제거되었습니다. 오직 <code>String.prototype.includes()</code>만 사용할 수 있습니다.</p> + +<h2 id="관련문서">관련문서</h2> + +<ul> + <li>{{jsxref("Array.prototype.includes()")}} {{experimental_inline}}</li> + <li>{{jsxref("TypedArray.prototype.includes()")}} {{experimental_inline}}</li> + <li>{{jsxref("String.prototype.indexOf()")}}</li> + <li>{{jsxref("String.prototype.lastIndexOf()")}}</li> + <li>{{jsxref("String.prototype.startsWith()")}}</li> + <li>{{jsxref("String.prototype.endsWith()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/index.html b/files/ko/web/javascript/reference/global_objects/string/index.html new file mode 100644 index 0000000000..68e9b021e5 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/index.html @@ -0,0 +1,298 @@ +--- +title: String +slug: Web/JavaScript/Reference/Global_Objects/String +tags: + - ECMAScript 2015 + - JavaScript + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String +--- +<div>{{JSRef}}</div> + +<p><strong><code>String</code></strong> 전역 객체는 문자열(문자의 나열)의 생성자입니다.</p> + +<h2 id="Syntax" name="Syntax">구문</h2> + +<p>문자열 리터럴은 다음과 같은 형식을 사용합니다.</p> + +<pre class="syntaxbox">'string text' +"string text" +"中文 español Deutsch English देवनागरी العربية português বাংলা русский 日本語 norsk bokmål ਪੰਜਾਬੀ 한국어 தமிழ் עברית"</pre> + +<p>문자열은 <code>String</code> 전역 객체를 직접 사용하여 생성할 수 있습니다.</p> + +<pre class="syntaxbox">String(<em>thing</em>)</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>thing</code></dt> + <dd>문자열로 변환할 아무 값.</dd> + <dt> + <h3 id="템플릿_리터럴">템플릿 리터럴</h3> + </dt> +</dl> + +<p>ECMAScript 2015 이후, 문자열 리터럴은 소위 <a href="/ko/docs/Web/JavaScript/Reference/Template_literals">템플릿 리터럴</a>이 될 수 있습니다.</p> + +<pre class="language-html"><code class="language-html">`hello world` `hello! world!` `hello ${who}` tag `<span class="tag token"><span class="tag token"><span class="punctuation token"><</span>a</span><span class="punctuation token">></span></span>${who}<span class="tag token"><span class="tag token"><span class="punctuation token"></</span>a</span><span class="punctuation token">></span></span>`</code></pre> + +<h3 id="이스케이프_표현">이스케이프 표현</h3> + +<p>일반적인 출력 문자 외의 특수 문자는 이스케이프 표현을 사용해 적을 수 있습니다.</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">코드</th> + <th scope="col">출력</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>\XXX</code></td> + <td>8진수 Latin-1 문자</td> + </tr> + <tr> + <td><code>\'</code></td> + <td>작은따옴표</td> + </tr> + <tr> + <td><code>\"</code></td> + <td>큰따옴표</td> + </tr> + <tr> + <td><code>\\</code></td> + <td>역슬래시</td> + </tr> + <tr> + <td><code>\n</code></td> + <td>개행</td> + </tr> + <tr> + <td><code>\r</code></td> + <td>캐리지 리턴</td> + </tr> + <tr> + <td><code>\v</code></td> + <td>세로 탭</td> + </tr> + <tr> + <td><code>\t</code></td> + <td>탭</td> + </tr> + <tr> + <td><code>\b</code></td> + <td>백 스페이스</td> + </tr> + <tr> + <td><code>\f</code></td> + <td>폼 피드</td> + </tr> + <tr> + <td><code>\uXXXX</code></td> + <td>유니코드 코드포인트</td> + </tr> + <tr> + <td><code>\u{X}</code> ... <code>\u{XXXXXX}</code></td> + <td>유니코드 코드포인트 {{experimental_inline}}</td> + </tr> + <tr> + <td><code>\xXX</code></td> + <td>Latin-1 문자</td> + </tr> + </tbody> +</table> + +<div class="note"> +<p>일부 다른 프로그래밍 언어와 달리, JavaScript는 작은따옴표와 큰따옴표 문자열을 구분하지 않습니다. 따라서 위의 이스케이프 문자는 작은따옴표나 큰따옴표에서 상관 없이 작동합니다.</p> +</div> + +<h3 id="긴_문자열_리터럴">긴 문자열 리터럴</h3> + +<p>작성한 코드가 매우 긴 문자열을 포함해야 하는 경우, 끝 없이 뻗어나가는 한 줄이나 편집기의 재량에 따라 자동으로 줄을 넘기는 대신 직접 여러 줄로 나누되 내용에는 영향을 주지 않고 싶을 때가 있을겁니다. 이런 상황에는 두 가지 방법을 사용할 수 있습니다.</p> + +<p>우선 다음과 같이 <a href="/ko/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#%EB%8D%94%ED%95%98%EA%B8%B0_()">+</a> 연산자를 사용할 수 있습니다.</p> + +<pre class="brush: js"><code>let longString = "여러 줄에 걸쳐 작성해야 할 정도로 " + + "긴 문자열인데 왜 한 줄에 다 적으면 안되냐면 " + + "코드를 읽기 힘들어지니까요.";</code></pre> + +<p>아니면 역슬래시 문자("\")를 각 줄의 맨 끝에 붙여 문자열이 이어진다는걸 표시할 수도 있습니다. 역슬래시 다음에 공백을 포함한 어떤 문자라도 붙으면 제대로 작동하지 않으므로 주의해야 합니다.</p> + +<pre class="brush: js"><code>let longString = "여러 줄에 걸쳐 작성해야 할 정도로 \ +긴 문자열인데 왜 한 줄에 다 적으면 안되냐면 \ +코드를 읽기 힘들어지니까요.";</code></pre> + +<p>두 예시 모두 동일한 문자열을 생성합니다.</p> + +<h2 id="Description" name="Description">설명</h2> + +<p>문자열은 텍스트 형태로 표현될 수있는 데이터를 보관하는 데 유용합니다. 문자열에서 가장 많이 사용되는 작업들은 문자열의 길이를 확인하는 ({{jsxref("String.length", "length")}}), 문자열을 생성하고 연결하는 <a href="/ko/docs/Web/JavaScript/Reference/Operators/String_Operators" title="JavaScript/Reference/Operators/String_Operators">+ 와 += 문자열 연산자</a>, 서브문자열(substring)이 있는지 확인하고, 있으면 위치를 확인하는 {{jsxref("String.prototype.indexOf()", "indexOf()")}} 메서드, 서브문자열(substring)을 추출해내는 {{jsxref("String.prototype.substring()", "substring()")}} 메서드가 있습니다.</p> + +<h3 id="문자_접근">문자 접근</h3> + +<p>문자열에서 개개의 문자에 접근할 수 있는 방법은 두가지가 있습니다. 첫번째는 {{jsxref("String.prototype.charAt()", "charAt()")}} 메서드를 이용하는 것입니다:</p> + +<pre class="brush: js">return 'cat'.charAt(1); // returns "a" +</pre> + +<p>다른 방법(ECMAScript 5에서 소개하고 있는)은 문자열을 배열과 같은 오브젝트로 취급하여, 문자에 해당하는 숫자 인덱스를 사용하는 방법입니다 :</p> + +<pre class="brush: js">return 'cat'[1]; // returns "a" +</pre> + +<p>브라켓([ ]) 표기법을 사용하여 문자에 접근하는 경우 , 이러한 프로퍼티들에 새로운 값을 할당하거나 삭제할 수는 없습니다. 포함되어 있는 프로퍼티들은 작성할 수도, 수정할 수도 없습니다. (더 자세한 정보는 {{jsxref("Object.defineProperty()")}}를 참고 바랍니다 .)</p> + +<h3 id="Comparing_strings" name="Comparing_strings">문자열 비교</h3> + +<p>C 개발자는 문자열 비교를 위하여 <code><span style="font-family: courier new,andale mono,monospace;">strcmp()</span></code> 함수를 사용합니다. JavaScript에서는 단지 <a href="/ko/docs/Web/JavaScript/Reference/Operators/Comparison_Operators" style="line-height: inherit;" title="JavaScript/Reference/Operators/Comparison_Operators">less-than와 greater-than 연산자</a>만을 사용하여 문자열을 비교할 수 있습니다<span style="line-height: inherit;"> </span><span style="line-height: inherit;">:</span></p> + +<pre class="brush: js">var a = "a"; +var b = "b"; +if (a < b) { // true + console.log(a + " is less than " + b); +} else if (a > b) { + console.log(a + " is greater than " + b); +} else { + console.log(a + " and " + b + " are equal."); +} +</pre> + +<p>비슷한 결과를 얻을 수 있는 방법으로 <span style="font-family: courier new,andale mono,monospace;">String</span> 인스턴스에서 상속된 {{jsxref("String.prototype.localeCompare()", "localeCompare()")}} 메서드를 사용할 수 있습니다.</p> + +<h3 id="문자열_원형과_String_객체의_차이">문자열 원형과 <code>String</code> 객체의 차이</h3> + +<div>JavaScript는 <code>String</code> 오브젝트와 원형의 문자열을 다르게 취급한다는 것에 주의해야 합니다. ({{jsxref("Boolean")}}과 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects" title="JavaScript/Reference/Global_Objects/">숫자</a>의 true도 마찬가지입니다.)</div> + +<div> </div> + +<p>문자열 리터럴(작은 따옴표 또는 큰 따옴표로 생성되는)과 생성자 없이(즉. {{jsxref("Operators/new", "new")}} 키워드를 사용하지 않고) <code>String</code>을 호출하여 반환된 문자열은 원형 문자열(primitive strings)입니다. JavaScript는 자동적으로 원형을 <code>String</code> 오브젝트로 변환하기 때문에, <code>String</code> 오브젝트 메서드를 사용하여 원형문자열을 생성할 수 있습니다. 문맥 안의 메서드에서 프로퍼티 조회 또는 원형의 문자열 호출이 발생하면, JavaScript는 자동으로 문자열 원형을 감싸고 프로퍼티 조회를 수행 하거나 메서드를 호출합니다.</p> + +<pre class="brush: js">var s_prim = "foo"; +var s_obj = new String(s_prim); + +console.log(typeof s_prim); // Logs "string" +console.log(typeof s_obj); // Logs "object" +</pre> + +<p>문자열 원형과 <code>String</code> 오브젝트는 {{jsxref("Global_Objects/eval", "eval()")}}을 사용할 때 다른 결과를 제공합니다. <code>eval</code>에 전달되는 문자열 원형들은 소스 코드 취급을 받습니다; <code>String</code> 오브젝트들은 다른 모든 오브젝트들과 마찬가지로 취급하며, 오브젝트를 반환합니다. 예를 들면:</p> + +<pre class="brush: js">var s1 = '2 + 2'; // creates a string primitive +var s2 = new String('2 + 2'); // creates a String object +console.log(eval(s1)); // returns the number 4 +console.log(eval(s2)); // returns the string "2 + 2" +</pre> + +<p>이러한 이유로, 비록 코드 상에서 원형 문자열을 사용하는 대신에 <code>String</code> 오브젝트를 사용하게 되면 코드가 손상될 수 있지만, 일반적인 개발자는 차이를 걱정할 필요는 없습니다.</p> + +<p><code>String</code><span style="line-height: inherit;"> 오프젝트는 언제든지 </span>{{jsxref("String.prototype.valueOf()", "valueOf()")}} <span style="line-height: inherit;"> 메서드로 원형에 대응하도록 전환할 수 있습니다.</span></p> + +<pre class="brush: js">console.log(eval(s2.valueOf())); // returns the number 4 +</pre> + +<h2 id="Properties" name="Properties">속성</h2> + +<dl> + <dt>{{jsxref("String.prototype")}}</dt> + <dd>String 오브젝트는 프로퍼티의 추가가 가능합니다.</dd> +</dl> + +<h2 id="Methods" name="Methods">메서드</h2> + +<dl> + <dt>{{jsxref("String.fromCharCode()")}}</dt> + <dd>지정된 유니코 값의 순서를 이용하여 만든 문자열을 반환합니다.</dd> + <dt>{{jsxref("String.fromCodePoint()")}} {{experimental_inline}}</dt> + <dd>지정된 코드 포인트 순서를 이용하여 만든 문자열을 반환합니다.</dd> + <dt>{{jsxref("String.raw()")}} {{experimental_inline}}</dt> + <dd>원형 템플릿 문자열(raw template string)에서 생성된 문자열을 반환합니다.</dd> +</dl> + +<h2 id="String_generic_메서드"><code>String</code> generic 메서드</h2> + +<div class="warning"> +<p><strong><code>String</code> generic들은 비표준으로, 가까운 미래에 사라질 것입니다.</strong> 아래에서 제공하고 있는 방식을 사용하지 않으면, 브라우저들간의 호환성은 기대하기 어렵습니다. </p> +</div> + +<p><code>String</code><span style="line-height: inherit;"> 인스턴스 메서드는 JavScript 1.6으로 Firefox에서(ECMAScript 표준에 속하지는 않지만) 어떤 오브젝트라도 String 메서드에 적용하여 String 오브젝트에서 사용가능합니다:</span></p> + +<pre class="brush: js">var num = 15; +console.log(String.replace(num, /5/, '2')); +</pre> + +<p class="brush: js">{{jsxref("Global_Objects/Array", "Generics", "#Array_generic_methods", 1)}}은<span style="line-height: inherit;"> </span>{{jsxref("Global_Objects/Array", "Array")}}<span style="line-height: inherit;"> 메서드에도 사용 가능합니다.</span></p> + +<h2 id="String_instances" name="String_instances"><code>String</code> 인스턴스</h2> + +<h3 id="속성">속성</h3> + +<p>{{ page('ko/docs/JavaScript/Reference/Global_Objects/String/prototype', 'Properties') }}</p> + +<h3 id="메서드">메서드</h3> + +<h4 id="HTML과_관계없는_메서드">HTML과 관계없는 메서드</h4> + +<p>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Methods_unrelated_to_HTML')}}</p> + +<h4 id="HTML_wrapper_methods">HTML wrapper methods</h4> + +<p>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'HTML_wrapper_methods')}}</p> + +<h2 id="예제">예제</h2> + +<h3 id="문자열_변환">문자열 변환</h3> + +<p>비록 일반적으로 toString() 함수를 많이 사용하고 있지만, {{jsxref("String.prototype.toString()", "toString()")}}의 "안전한" 대안으로 String을 사용할 수 있습니다. String은 {{jsxref("Global_Objects/null", "null")}}과 {{jsxref("Global_Objects/undefined", "undefined")}}에 대해서도 잘 동작합니다. 예를 들면: </p> + +<pre class="brush: js">var outputStrings = []; +for (var i = 0, n = inputValues.length; i < n; ++i) { + outputStrings.push(String(inputValues[i])); +} +</pre> + +<h2 id="Browser_Compatibility" name="Browser_Compatibility">명세</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('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5', 'String')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string-objects', 'String')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string-objects', 'String')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_Compatibility" name="Browser_Compatibility">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.String",2)}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{domxref("DOMString")}}</li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/DOMString/Binary">Binary strings</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/indexof/index.html b/files/ko/web/javascript/reference/global_objects/string/indexof/index.html new file mode 100644 index 0000000000..3e12f74d51 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/indexof/index.html @@ -0,0 +1,159 @@ +--- +title: String.prototype.indexOf() +slug: Web/JavaScript/Reference/Global_Objects/String/indexOf +tags: + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/indexOf +--- +<div>{{JSRef}}</div> + +<p><strong><code>indexOf()</code></strong> 메서드는 호출한 {{jsxref("String")}} 객체에서 주어진 값과 일치하는 첫 번째 인덱스를 반환합니다. 일치하는 값이 없으면 -1을 반환합니다. </p> + +<div>{{EmbedInteractiveExample("pages/js/string-indexof.html")}}</div> + + + +<div class="note"> +<p><strong>참고:</strong> {{jsxref("Array")}}에서는 {{jsxref("Array.prototype.indexOf()")}} 메서드가 같은 역할을 합니다.</p> +</div> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>str</var>.indexOf(<var>searchValue</var>[, <var>fromIndex</var>])</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>searchValue</code></dt> + <dd>찾으려는 문자열. 아무 값도 주어지지 않으면 <a href="https://tc39.github.io/ecma262/#sec-tostring">문자열 <code>"undefined"</code>를 찾으려는 문자열로 사용</a>합니다.</dd> + <dt><code>fromIndex</code> {{optional_inline}}</dt> + <dd>문자열에서 찾기 시작하는 위치를 나타내는 인덱스 값입니다. 어떤 정수값이라도 가능합니다. 기본값은 0이며, 문자열 전체를 대상으로 찾게 됩니다. 만약 <code>fromIndex </code>값이 음의 정수이면 전체 문자열을 찾게 됩니다. 만약 <code>fromIndex >= str.length </code>이면, 검색하지 않고 바로 -1을 반환합니다. <code>searchValue</code>가 공백 문자열이 아니라면, <code>str.length</code>를 반환합니다.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p><code>searchValue</code>의 첫 번째 등장 인덱스. 찾을 수 없으면 -1.</p> + +<h2 id="설명">설명</h2> + +<p>문자열 내에 있는 문자들은 왼쪽에서 오른쪽 방향으로 순번이 매겨집니다. 제일 처음 문자는 0번째 순번(index)이며, <code>stringName </code>문자열의 마지막 문자의 순번 <code>stringName.length -1</code> 입니다. </p> + +<pre class="brush: js">'Blue Whale'.indexOf('Blue'); // returns 0 +'Blue Whale'.indexOf('Blute'); // returns -1 +'Blue Whale'.indexOf('Whale', 0); // returns 5 +'Blue Whale'.indexOf('Whale', 5); // returns 5 +'Blue Whale'.indexOf('Whale', 7); // returns -1 +'Blue Whale'.indexOf(''); // returns 0 +'Blue Whale'.indexOf('', 9); // returns 9 +'Blue Whale'.indexOf('', 10); // returns 10 +'Blue Whale'.indexOf('', 11); // returns 10</pre> + +<p><code>indexOf()</code> 메서드는 대소문자를 구분합니다. 예를 들면, 아래 예제는 일치하는 문자열이 없으므로 <code>-1</code>을 반환합니다.</p> + +<pre class="brush: js">'Blue Whale'.indexOf('blue'); // returns -1 +</pre> + +<h3 id="존재_여부_확인">존재 여부 확인</h3> + +<p>'0'을 평가했을 때 <code>true</code>가 아니고, -1을 평가했을 때 <code>false</code>가 아닌 것에 주의해야 합니다. 따라서, 임의의 문자열에 특정 문자열이 있는지를 확인하는 올바른 방법은 다음과 같습니다.</p> + +<pre class="brush: js">'Blue Whale'.indexOf('Blue') !== -1; // true +'Blue Whale'.indexOf('Bloe') !== -1; // false +</pre> + +<h2 id="예제">예제</h2> + +<h3 id="indexOf()_사용하기"><code>indexOf()</code> 사용하기</h3> + +<p>아래 예제는 <code>"Brave new world"</code> 문자열의 위치를 확인하기 위해 <code>indexOf()</code>와 {{jsxref("String.prototype.lastIndexOf()", "lastIndexOf()")}} 를 사용하고 있습니다.</p> + +<pre class="brush: js">var anyString = 'Brave new world'; + +console.log('The index of the first w from the beginning is ' + anyString.indexOf('w')); +// 첫번째 w 문자 위치는 8 +console.log('The index of the first w from the end is ' + anyString.lastIndexOf('w')); +// 마지막 w 문자 위치는 10 + +console.log('The index of "new" from the beginning is ' + anyString.indexOf('new')); +// 첫번째 new 문자열 위치는 6 +console.log('The index of "new" from the end is ' + anyString.lastIndexOf('new')); +// 마지막 new 문자열 위치는 6 +</pre> + +<h3 id="indexOf()와_대소문자_구분"><code>indexOf()</code>와 대소문자 구분</h3> + +<p>아래 예제에서는 2개의 문자열 변수를 정의하고 있습니다. 이 변수들 내에 있는 문자열들은 모두 같지만 두 번째 변수에 포함되어 있는 문자열은 대문자를 포함하고 있습니다. 첫 번째 {{domxref("console.log()")}} 메서드의 결과값은 19입니다. 하지만, 두 번째 <code>console.log()</code> 메서드의 결과값은 <code>-1</code>입니다. 왜냐하면, indexOf() 메서드는 대소문자를 구분하기 때문에 <code>myCapString</code>에서 "<code>cheddar</code>" 문자열을 찾을 수 없기 때문입니다. </p> + +<pre class="brush: js">var myString = 'brie, pepper jack, cheddar'; +var myCapString = 'Brie, Pepper Jack, Cheddar'; + +console.log('myString.indexOf("cheddar") is ' + myString.indexOf('cheddar')); +// 로그에 19를 출력합니다. +console.log('myCapString.indexOf("cheddar") is ' + myCapString.indexOf('cheddar')); +// 로그에 -1을 출력합니다. +</pre> + +<h3 id="indexOf()를_사용하여_문자열_내의_특정_문자_숫자_세기"><code>indexOf()</code>를 사용하여 문자열 내의 특정 문자 숫자 세기</h3> + +<p>아래 예제는 <code>str </code>문자열에서 <code>e </code>문자의 총 숫자를 확인하는 프로그램입니다:</p> + +<pre class="brush: js">var str = 'To be, or not to be, that is the question.'; +var count = 0; +var pos = str.indexOf('e'); //pos는 4의 값을 가집니다. + +while (pos !== -1) { + count++; + pos = str.indexOf('e', pos + 1); // 첫 번째 e 이후의 인덱스부터 e를 찾습니다. +} + +console.log(count); // 로그에 4를 출력합니다. +</pre> + +<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('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.7', 'String.prototype.indexOf')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.indexof', 'String.prototype.indexOf')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.indexof', 'String.prototype.indexOf')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{Compat("javascript.builtins.String.indexOf")}}</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("String.prototype.charAt()")}}</li> + <li>{{jsxref("String.prototype.lastIndexOf()")}}</li> + <li>{{jsxref("String.prototype.split()")}}</li> + <li>{{jsxref("Array.prototype.indexOf()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/lastindexof/index.html b/files/ko/web/javascript/reference/global_objects/string/lastindexof/index.html new file mode 100644 index 0000000000..d2244feee5 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/lastindexof/index.html @@ -0,0 +1,105 @@ +--- +title: String.prototype.lastIndexOf() +slug: Web/JavaScript/Reference/Global_Objects/String/lastIndexOf +tags: + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/lastIndexOf +--- +<div>{{JSRef}}</div> + +<p><strong><code>lastIndexOf()</code></strong> 메서드는 주어진 값과 일치하는 부분을 <code>fromIndex</code>로부터 역순으로 탐색하여, 최초로 마주치는 인덱스를 반환합니다. 일치하는 부분을 찾을 수 없으면 <code>-1</code>을 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/string-lastindexof.html", "shorter")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox notranslate"><var>str</var>.lastIndexOf(<var>searchValue</var>[, <var>fromIndex</var>])</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>searchValue</code></dt> + <dd>탐색할 문자열. 빈 값을 제공할 경우 <code>fromIndex</code>를 반환합니다.</dd> + <dt><code>fromIndex</code> {{optional_inline}}</dt> + <dd>탐색의 시작점으로 사용할 인덱스. 기본값은 <code>+Infinity</code>입니다. <code>fromIndex >= str.length</code>인 경우 모든 문자열을 탐색합니다. <code>fromIndex < 0</code>인 경우엔 <code>0</code>을 지정한 것과 동일합니다.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>문자열 내에서 searchValue가 마지막으로 등장하는 인덱스. 등장하지 않으면 <code>-1</code>.</p> + +<h2 id="설명">설명</h2> + +<p>문자열의 문자는 왼쪽에서 오른쪽으로 인덱스를 매깁니다. 첫 번째 문자의 인덱스는 <code>0</code>이며, 마지막 문자의 인덱스는 <code>str.length -1</code>입니다.</p> + +<pre class="brush: js notranslate">'canal'.lastIndexOf('a'); // 3 반환 +'canal'.lastIndexOf('a', 2); // 1 반환 +'canal'.lastIndexOf('a', 0); // -1 반환 +'canal'.lastIndexOf('x'); // -1 반환 +'canal'.lastIndexOf('c', -5); // 0 반환 +'canal'.lastIndexOf('c', 0); // 0 반환 +'canal'.lastIndexOf(''); // 5 반환 +'canal'.lastIndexOf('', 2); // 2 반환 +</pre> + +<div class="blockIndicator note"> +<p><strong>참고:</strong> <code>'abab'.lastIndexOf('ab', 2)</code>는 0이 아니고 2를 반환합니다. <code>fromIndex</code>는 탐색의 시작점만 제한하기 때문입니다.</p> +</div> + +<h3 id="대소문자_구분">대소문자 구분</h3> + +<p><code>lastIndexOf()</code> 메서드는 대소문자를 구분합니다. 예를 들어, 아래 예제는 <code>-1</code>을 반환합니다.</p> + +<pre class="brush: js notranslate">'Blue Whale, Killer Whale'.lastIndexOf('blue'); // -1 반환 +</pre> + +<h2 id="예제">예제</h2> + +<h3 id="indexOf와_lastIndexOf_사용하기"><code>indexOf()</code>와 <code>lastIndexOf()</code> 사용하기</h3> + +<p>아래 예제는 문자열 <code>"Brave new world"</code> 내에서 특정 값의 위치를 확인하기 위해 {{jsxref("String.prototype.indexOf()", "indexOf()")}}와 <code>lastIndexOf()</code>를 사용합니다.</p> + +<pre class="brush: js notranslate">let anyString = 'Brave new world'; + +console.log('시작점으로부터 처음 만나는 w의 위치는 ' + anyString.indexOf('w')); +// logs 8 +console.log('끝점으로부터 처음 만나는 w의 위치는 ' + anyString.lastIndexOf('w')); +// logs 10 +console.log('시작점으로부터 처음 만나는 "new"의 위치는 ' + anyString.indexOf('new')); +// logs 6 +console.log('끝점으로부터 처음 만나는 "new"의 위치는 ' + anyString.lastIndexOf('new')); +// logs 6 +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.lastindexof', 'String.prototype.lastIndexOf')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{Compat("javascript.builtins.String.lastIndexOf")}}</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("String.prototype.charAt()")}}</li> + <li>{{jsxref("String.prototype.indexOf()")}}</li> + <li>{{jsxref("String.prototype.split()")}}</li> + <li>{{jsxref("Array.prototype.indexOf()")}}</li> + <li>{{jsxref("Array.prototype.lastIndexOf()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/length/index.html b/files/ko/web/javascript/reference/global_objects/string/length/index.html new file mode 100644 index 0000000000..697957aaf9 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/length/index.html @@ -0,0 +1,84 @@ +--- +title: String.length +slug: Web/JavaScript/Reference/Global_Objects/String/length +tags: + - JavaScript + - Property + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/length +--- +<div>{{JSRef}}</div> + +<p><strong><code>length</code></strong> 속성은 UTF-16 코드 유닛을 기준으로 문자열의 길이를 나타냅니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/string-length.html")}}</div> + + + +<h2 id="설명">설명</h2> + +<p><code>length</code> 속성은 문자열 안의 코드 유닛 수를 반환합니다. JavaScript가 사용하는 문자열 형식인 {{interwiki("wikipedia", "UTF-16")}}은 대부분의 일반적인 문자를 표현하기 위해 하나의 16비트 코드 유닛을 사용합니다. 반면, 덜 쓰이는 문자를 표현하기 위해 2개의 코드 유닛을 사용해야 할 때도 있으므로 문자열 내에 있는 문자들의 실제 총 숫자가 <code>length</code> 속성이 반환하는 숫자와 일치하지 않을 수 있습니다.</p> + +<p>ECMAScript 2016 7판은 최대 길이를 <code>2^53 - 1</code>로 설정했습니다. 이전엔 명시된 최대 길이가 없었습니다.</p> + +<p>빈 문자열은 <code>length</code>가 0입니다.</p> + +<p>정적 속성 <code>String.length</code>는 1을 반환합니다. </p> + +<h2 id="예제">예제</h2> + +<h3 id="일반적인_사용법">일반적인 사용법</h3> + +<pre class="brush: js">var x = 'Mozilla'; +var empty = ''; + +console.log('Mozilla는 코드 유닛 ' + x.length + '개의 길이입니다.'); +/* "Mozilla는 코드 유닛 7개의 길이입니다." */ + +console.log('빈 문자열은 ' + empty.length + '의 길이를 가집니다.'); +/* "빈 문자열은 0의 길이를 가집니다." */ +</pre> + +<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('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.5.1', 'String.prototype.length')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-properties-of-string-instances-length', 'String.prototype.length')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-properties-of-string-instances-length', 'String.prototype.length')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{Compat("javascript.builtins.String.length")}}</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="http://developer.teradata.com/blog/jasonstrimpel/2011/11/javascript-string-length-and-internationalizing-web-applications">JavaScript <code>String.length</code> and Internationalizing Web Applications</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/localecompare/index.html b/files/ko/web/javascript/reference/global_objects/string/localecompare/index.html new file mode 100644 index 0000000000..9bd3b19236 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/localecompare/index.html @@ -0,0 +1,159 @@ +--- +title: String.prototype.localeCompare() +slug: Web/JavaScript/Reference/Global_Objects/String/localeCompare +translation_of: Web/JavaScript/Reference/Global_Objects/String/localeCompare +--- +<div>{{JSRef}}</div> + +<p>The <strong><code>localeCompare()</code></strong> 메서드는 기준 문자열과 비교했을 때 비교 대상 문자열이 정렬상 전에 오는지, 후에 오는지 혹은 같은 순서에 배치되는지를 알려주는 숫자를 리턴합니다.</p> + +<p>The new <code>locales</code> and <code>options</code> arguments let applications specify the language whose sort order should be used and customize the behavior of the function. In older implementations, which ignore the <code>locales</code> and <code>options</code> arguments, the locale and sort order used are entirely implementation dependent.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code><var>referenceStr</var>.localeCompare(<var>compareString</var>[, <var>locales</var>[, <var>options</var>]])</code></pre> + +<h3 id="Parameters">Parameters</h3> + +<p>Check the <a href="#Browser_compatibility">Browser compatibility</a> section to see which browsers support the <code>locales</code> and <code>options</code> arguments, and the <a href="#Checking_for_support_for_locales_and_options_arguments">Checking for support for <code>locales</code> and <code>options</code> arguments</a> for feature detection.</p> + +<dl> + <dt><code>compareString</code></dt> + <dd>The string against which the referring string is compared</dd> +</dl> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Collator', 'Parameters')}}</div> + +<h3 id="Return_value">Return value</h3> + +<p>A <strong>negative</strong> number if the reference string occurs before the compare string; <strong>positive</strong> if the reference string occurs after the compare string; <strong>0</strong> if they are equivalent.</p> + +<h2 id="Description">Description</h2> + +<p>Returns an integer indicating whether the <strong>referenceStr</strong> comes before, after or is equivalent to the <strong>compareStr</strong>.</p> + +<ul> + <li>Negative when the <strong>referenceStr</strong> occurs before <strong>compareStr</strong></li> + <li>Positive when the <strong>referenceStr</strong> occurs after <strong>compareStr</strong></li> + <li>Returns 0 if they are equivalent</li> +</ul> + +<p><strong>DO NOT rely on exact return values of -1 or 1. </strong>Negative and positive integer results vary between browsers (as well as between browser versions) because the W3C specification only mandates negative and positive values. Some browsers may return -2 or 2 or even some other negative or positive value.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_localeCompare()">Using <code>localeCompare()</code></h3> + +<pre class="brush: js">// The letter "a" is before "c" yielding a negative value +'a'.localeCompare('c'); // -2 or -1 (or some other negative value) + +// Alphabetically the word "check" comes after "against" yielding a positive value +'check'.localeCompare('against'); // 2 or 1 (or some other positive value) + +// "a" and "a" are equivalent yielding a neutral value of zero +'a'.localeCompare('a'); // 0 +</pre> + +<h3 id="Sort_an_array">Sort an array</h3> + +<p><code>localeCompare</code> enables a case-insensitive sort of an array.</p> + +<pre class="brush: js">var items = ['réservé', 'premier', 'cliché', 'communiqué', 'café', 'adieu']; +items.sort((a, b) => a.localeCompare(b)); // ['adieu', 'café', 'cliché', 'communiqué', 'premier', 'réservé'] +</pre> + +<h3 id="Check_browser_support_for_extended_arguments">Check browser support for extended arguments</h3> + +<p>The <code>locales</code> and <code>options</code> arguments are not supported in all browsers yet. To check whether an implementation supports them, use the "i" argument (a requirement that illegal language tags are rejected) and look for a {{jsxref("RangeError")}} exception:</p> + +<pre class="brush: js">function localeCompareSupportsLocales() { + try { + 'foo'.localeCompare('bar', 'i'); + } catch (e) { + return e.name === 'RangeError'; + } + return false; +} +</pre> + +<h3 id="Using_locales">Using <code>locales</code></h3> + +<p>The results provided by <code>localeCompare()</code> vary between languages. In order to get the sort order of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the <code>locales</code> argument:</p> + +<pre class="brush: js">console.log('ä'.localeCompare('z', 'de')); // a negative value: in German, ä sorts before z +console.log('ä'.localeCompare('z', 'sv')); // a positive value: in Swedish, ä sorts after z +</pre> + +<h3 id="Using_options">Using <code>options</code></h3> + +<p>The results provided by <code>localeCompare()</code> can be customized using the <code>options</code> argument:</p> + +<pre class="brush: js">// in German, ä has a as the base letter +console.log('ä'.localeCompare('a', 'de', { sensitivity: 'base' })); // 0 + +// in Swedish, ä and a are separate base letters +console.log('ä'.localeCompare('a', 'sv', { sensitivity: 'base' })); // a positive value +</pre> + +<h2 id="Performance">Performance</h2> + +<p>When comparing large numbers of strings, such as in sorting large arrays, it is better to create an {{jsxref("Global_Objects/Collator", "Intl.Collator")}} object and use the function provided by its {{jsxref("Collator.prototype.compare", "compare")}} property.</p> + +<h2 id="Specifications">Specifications</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.9', 'String.prototype.localeCompare')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.localecompare', 'String.prototype.localeCompare')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.localecompare', 'String.prototype.localeCompare')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES Int 1.0', '#sec-13.1.1', 'String.prototype.localeCompare')}}</td> + <td>{{Spec2('ES Int 1.0')}}</td> + <td><code>locale</code> and <code>option</code> parameter definitions.</td> + </tr> + <tr> + <td>{{SpecName('ES Int 2.0', '#sec-13.1.1', 'String.prototype.localeCompare')}}</td> + <td>{{Spec2('ES Int 2.0')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES Int Draft', '#sec-String.prototype.localeCompare', 'String.prototype.localeCompare')}}</td> + <td>{{Spec2('ES Int Draft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.localeCompare")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Global_Objects/Collator", "Intl.Collator")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/match/index.html b/files/ko/web/javascript/reference/global_objects/string/match/index.html new file mode 100644 index 0000000000..e1031b8a0e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/match/index.html @@ -0,0 +1,156 @@ +--- +title: String.prototype.match() +slug: Web/JavaScript/Reference/Global_Objects/String/match +translation_of: Web/JavaScript/Reference/Global_Objects/String/match +--- +<div>{{JSRef}}</div> + +<div></div> + +<p><strong><code>match()</code></strong> 메서드는 문자열이 정규식과 매치되는 부분을 검색합니다.</p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox"><var>str</var>.match(<var>regexp</var>)</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>regexp</code></dt> + <dd>정규식 개체입니다. RegExp가 아닌 객체 obj가 전달되면, <code>new RegExp(obj)</code>를 사용하여 암묵적으로 {{jsxref("RegExp")}}로 변환됩니다. 매개변수를 전달하지 않고 match()를 사용하면, 빈 문자열:[""]이 있는 {{jsxref("Array")}}가 반환됩니다.</dd> +</dl> + +<h3 id="결과_값">결과 값</h3> + +<p>문자열이 정규식과 일치하면, 일치하는 전체 문자열을 첫 번째 요소로 포함하는 {{jsxref("Array")}}를 반환한 다음 괄호 안에 캡처된 결과가 옵니다. 일치하는 것이 없으면 {{jsxref("null")}}이 반환됩니다.</p> + +<h2 id="설명">설명</h2> + +<p>정규식에 <code>g</code> 플래그가 포함되어있지 않으면, <code>str.match()</code> 는 {{jsxref("RegExp.prototype.exec()", "RegExp.exec()")}}와 같은 결과를 반환합니다. 반환된 {{jsxref("Array")}}는 원래 문자열의 값을 가지는 <code>input</code> 속성을 포함합니다. 그리고 문자열에서 제로 베이스의 인덱스를 나타내는 <code>index</code> 속성 또한 포함합니다.</p> + +<p>정규식에 <code>g</code> 플래그가 포함되어 있으면, 일치는 객체가 아닌 일치하는 하위 문자열을 포함하는 {{jsxref("Array")}}를 반환합니다. 캡처된 그룹은 반환되지 않습니다. 일치하는 것이 없으면 null이 반환됩니다.</p> + +<h3 id="이것도_보세요_RegExp_메서드">이것도 보세요: <code>RegExp</code> 메서드</h3> + +<ul> + <li>문자열이 정규표현식{{jsxref("RegExp")}}과 일치하는지 여부를 알아야할 때, {{jsxref("RegExp.prototype.test()", "RegExp.test()")}}을 이용해보세요.</li> + <li>일치하는 것 중 제일 첫번째 것만 알고싶을 때, {{jsxref("RegExp.prototype.exec()", "RegExp.exec()")}}을 대신에 사용하고 싶을겁니다.</li> + <li>캡처 그룹을 알고 싶고 전역 플래그가 셋팅되어 있다면, {{jsxref("RegExp.prototype.exec()", "RegExp.exec()")}}을 대신에 사용해야합니다.</li> +</ul> + +<h2 id="예제">예제</h2> + +<h3 id="match()_사용하기"><code>match()</code> 사용하기</h3> + +<p>다음 예제에서는, <code>match()</code>를 사용하여 <code>'Chapter'</code> 라는 단어와 그에 이어지는 1 이상의 숫자, 그리고 그에 이어서 소숫점, 숫자 형태가 반복되는 문자열을 찾는다. 이 정규표현식은 i 플래그를 사용함으로써, 대소문자 구분 없이 찾고자 하는 문자열을 찾는다.</p> + +<pre class="brush: js">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' 요소는 입력된 원래 문자열을 나타냄.</pre> + +<h3 id="match()와_함께_글로벌(g)_및_대소문자_무시(i)_플래그_사용하기"><code>match()</code>와 함께 글로벌(g) 및 대/소문자 무시(i) 플래그 사용하기</h3> + +<p>다음 예제는 글로벌(g) 및 대/소문자 무시(i) 플래그를 사용하여 <code>match()</code>를 사용하는 방법을 보여준다. A부터 E 까지의 모든 문자와 a부터 e 까지의 모든 문자가 배열의 각 원소를 구성하는 형태로 반환된다.</p> + +<pre class="brush: js">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'] +</pre> + +<h3 id="매개변수_없이_match()_사용하기">매개변수 없이 <code>match()</code> 사용하기</h3> + +<pre class="brush: js">var str = "Nothing will come of nothing."; + +str.match(); // returns [""]</pre> + +<h3 id="정규표현식이_아닌_객체를_매개변수로_사용하기">정규표현식이 아닌 객체를 매개변수로 사용하기</h3> + +<p>매개변수가 문자열이나 숫자(Number)이면, 해당 매개변수는 내부적으로 new RegExp(obj)를 사용하여 {{jsxref("RegExp")}}로 변환된다. 만약 매개변수가 플러스 기호와 이어지는 숫자형이라면, RegExp() 매서드는 플러스 기호를 무시한다. </p> + +<pre class="brush: js">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"]을 반환함.</pre> + +<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.10', 'String.prototype.match')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.match', 'String.prototype.match')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.match', 'String.prototype.match')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">이 페이지의 호환성 표는 구조화된 데이터를 기반으로 작성하였습니다. 데이터를 제공하고 싶으시다면, <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a>를 체크하시고, 풀 리퀘스트를 보내주시기 바랍니다.</p> + +<p>{{Compat("javascript.builtins.String.match")}}</p> + +<h2 id="Firefox-specific_notes">Firefox-specific notes</h2> + +<ul> +</ul> + +<ul> + <li><code>flags</code> was a non standard second argument only available in Gecko : <var>str</var>.match(<var>regexp, flags</var>)</li> + <li>Starting with Gecko 27 {{geckoRelease(27)}}, this method has been adjusted to conform with the ECMAScript specification. When <code>match()</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("RegExp")}}</li> + <li>{{jsxref("RegExp.prototype.exec()")}}</li> + <li>{{jsxref("RegExp.prototype.test()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/normalize/index.html b/files/ko/web/javascript/reference/global_objects/string/normalize/index.html new file mode 100644 index 0000000000..d44f9bec99 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/normalize/index.html @@ -0,0 +1,163 @@ +--- +title: String.prototype.normalize() +slug: Web/JavaScript/Reference/Global_Objects/String/normalize +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Prototype + - Reference + - String + - Unicode +translation_of: Web/JavaScript/Reference/Global_Objects/String/normalize +--- +<div>{{JSRef}}</div> + +<p><strong><code>normalize()</code></strong> 메서드는 주어진 문자열을 유니코드 정규화 방식(Unicode Normalization Form)에 따라 정규화된 형태로 반환합니다. 만약 주어진 값이 문자열이 아닐 경우에는 우선 문자열로 변환 후 정규화합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/string-normalize.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>str</var>.normalize([<var>form</var>])</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>form</code></dt> + <dd>유니코드 정규화 방식을 지정합니다. <code>"NFC"</code>, <code>"NFD"</code>, <code>"NFKC"</code>, <code>"NFKD"</code> 중 하나이며, 생략되거나 {{jsxref("undefined")}} 일 경우 <code>"NFC"</code>가 사용됩니다. + <ul> + <li><code>NFC</code> — 정규형 정준 결합(Normalization Form Canonical Composition).</li> + <li><code>NFD</code> — 정규형 정준 분해(Normalization Form Canonical Decomposition).</li> + <li><code>NFKC</code> — 정규형 호환성 결합(Normalization Form Compatibility Composition).</li> + <li><code>NFKD</code> — 정규형 호환성 분해(Normalization Form Compatibility Decomposition).</li> + </ul> + </dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 문자열을 유니코드 정규화 방식에 따라 정규화된 문자열로 반환합니다.</p> + +<h3 id="예외">예외</h3> + +<dl> + <dt>{{jsxref("RangeError")}}</dt> + <dd><code>form</code>이 위에서 명시된 값 중 하나가 아닐 경우 {{jsxref("RangeError")}} 에러가 발생합니다.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p><code>normalize()</code> 메서드는 문자열을 유니코드 정규화 방식에 따라 정규화된 형태로 반환합니다. 문자열의 값 자체에는 영향을 주지 않습니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="normalize()_사용하기"><code>normalize()</code> 사용하기</h3> + +<pre class="brush: js">// 원본 문자열 + +// U+1E9B: LATIN SMALL LETTER LONG S WITH DOT ABOVE +// U+0323: COMBINING DOT BELOW +var str = '\u1E9B\u0323'; + + +// 정규형 정준 결합 (NFC) + +// U+1E9B: LATIN SMALL LETTER LONG S WITH DOT ABOVE +// U+0323: COMBINING DOT BELOW +str.normalize('NFC'); // '\u1E9B\u0323' +str.normalize(); // 위와 같은 결과 + + +// 정규형 정준 분해 (NFD) + +// U+017F: LATIN SMALL LETTER LONG S +// U+0323: COMBINING DOT BELOW +// U+0307: COMBINING DOT ABOVE +str.normalize('NFD'); // '\u017F\u0323\u0307' + + +// 정규형 호환성 결합 (NFKC) + +// U+1E69: LATIN SMALL LETTER S WITH DOT BELOW AND DOT ABOVE +str.normalize('NFKC'); // '\u1E69' + + +// 정규형 호환성 분해 (NFKD) + +// U+0073: LATIN SMALL LETTER S +// U+0323: COMBINING DOT BELOW +// U+0307: COMBINING DOT ABOVE +str.normalize('NFKD'); // '\u0073\u0323\u0307' +</pre> + +<h3 id="한글에_normalize()_사용하기">한글에 <code>normalize()</code> 사용하기</h3> + +<pre class="brush: js">// 결합된 한글 문자열 + +// U+D55C: 한(HANGUL SYLLABLE HAN) +// U+AE00: 글(HANGUL SYLLABLE GEUL) +var first = '\uD55C\uAE00'; + + +// 정규형 정준 분해 (NFD) +// 정준 분해 결과 초성, 중성, 종성의 자소분리가 일어납니다. +// 일부 브라우저에서는 결과값 '한글'이 자소분리된 상태로 보여질 수 있습니다. + +// U+1112: ᄒ(HANGUL CHOSEONG HIEUH) +// U+1161: ᅡ(HANGUL JUNGSEONG A) +// U+11AB: ᆫ(HANGUL JONGSEONG NIEUN) +// U+1100: ᄀ(HANGUL CHOSEONG KIYEOK) +// U+1173: ᅳ(HANGUL JUNGSEONG EU) +// U+11AF: ᆯ(HANGUL JONGSEONG RIEUL) +var second = first.normalize('NFD'); // '\u1112\u1161\u11AB\u1100\u1173\u11AF' + + +// 정규형 정준 결합 (NFC) +// 정준 결합 결과 자소분리 되었던 한글이 결합됩니다. + +// U+D55C: 한(HANGUL SYLLABLE HAN) +// U+AE00: 글(HANGUL SYLLABLE GEUL) +var third = second.normalize('NFC'); // '\uD55C\uAE00' + + +console.log(second === third); // 같은 글자처럼 보이지만 false를 출력합니다. +</pre> + +<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('ES2015', '#sec-string.prototype.normalize', 'String.prototype.normalize')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>초기 정의.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.normalize', 'String.prototype.normalize')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.normalize")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="http://www.unicode.org/reports/tr15/">Unicode Standard Annex #15, Unicode Normalization Forms</a></li> + <li><a href="http://en.wikipedia.org/wiki/Unicode_equivalence">Unicode equivalence</a></li> + <li><a href="https://ko.wikipedia.org/wiki/%EC%9C%A0%EB%8B%88%EC%BD%94%EB%93%9C_%EC%A0%95%EA%B7%9C%ED%99%94">유니코드 정규화</a></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/padend/index.html b/files/ko/web/javascript/reference/global_objects/string/padend/index.html new file mode 100644 index 0000000000..1c027c1363 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/padend/index.html @@ -0,0 +1,99 @@ +--- +title: String.prototype.padEnd() +slug: Web/JavaScript/Reference/Global_Objects/String/padEnd +tags: + - JavaScript + - Method + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/padEnd +--- +<div>{{JSRef}}</div> + +<p><strong><code>padEnd()</code></strong> 메서드는 현재 문자열에 다른 문자열을 채워, 주어진 길이를 만족하는 새로운 문자열을 반환합니다. 채워넣기는 대상 문자열의 끝(우측)부터 적용됩니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/string-padend.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>str</var>.padEnd(<var>targetLength</var> [, <var>padString</var>])</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>targetLength</code></dt> + <dd>목표 문자열 길이. 현재 문자열의 길이보다 작다면 채워넣지 않고 그대로 반환.</dd> + <dt><code>padString</code> {{optional_inline}}</dt> + <dd>현재 문자열에 채워넣을 다른 문자열. 문자열이 너무 길어 목표 문자열 길이를 초과한다면 좌측 일부를 잘라서 넣음. 기본값은 " ". (U+0020)</dd> +</dl> + +<h3 id="반환값">반환값</h3> + +<p>끝부터 주어진 문자열로 채워 목표 길이를 만족하는 {{jsxref("String")}}</p> + +<h2 id="예시">예시</h2> + +<pre class="brush: js">'abc'.padEnd(10); // "abc " +'abc'.padEnd(10, "foo"); // "abcfoofoof" +'abc'.padEnd(6, "123456"); // "abc123" +'abc'.padEnd(1); // "abc"</pre> + +<h2 id="폴리필">폴리필</h2> + +<p>다른 모든 코드 이전에 아래 코드를 포함하면 지원하지 않는 플랫폼에서도 <code>String.prototype.padStart()</code> 메서드를 사용할 수 있습니다.</p> + +<pre class="brush: js">// https://github.com/uxitten/polyfill/blob/master/string.polyfill.js +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd +if (!String.prototype.padEnd) { + String.prototype.padEnd = function padEnd(targetLength,padString) { + targetLength = targetLength>>0; //floor if number or convert non-number to 0; + padString = String((typeof padString !== 'undefined' ? padString : ' ')); + if (this.length > targetLength) { + return String(this); + } + else { + targetLength = targetLength-this.length; + if (targetLength > padString.length) { + padString += padString.repeat(targetLength/padString.length); //append to original to ensure we are longer than needed + } + return String(this) + padString.slice(0,targetLength); + } + }; +} +</pre> + +<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('ESDraft', '#sec-string.prototype.padend', 'String.prototype.padEnd')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Initial definition in ECMAScript 2017.</td> + </tr> + <tr> + <td>{{SpecName('ES8', '#sec-string.prototype.padend', 'String.prototype.padEnd')}}</td> + <td>{{Spec2('ES8')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.padEnd")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("String.prototype.padStart()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/padstart/index.html b/files/ko/web/javascript/reference/global_objects/string/padstart/index.html new file mode 100644 index 0000000000..eff03dd4ac --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/padstart/index.html @@ -0,0 +1,104 @@ +--- +title: String.prototype.padStart() +slug: Web/JavaScript/Reference/Global_Objects/String/padStart +tags: + - JavaScript + - Method + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/padStart +--- +<div>{{JSRef}}</div> + +<p><strong><code>padStart()</code></strong> 메서드는 현재 문자열의 시작을 다른 문자열로 채워, 주어진 길이를 만족하는 새로운 문자열을 반환합니다. 채워넣기는 대상 문자열의 시작(좌측)부터 적용됩니다.</p> + +<p> </p> + +<div>{{EmbedInteractiveExample("pages/js/string-padstart.html")}}</div> + + + +<p> </p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>str</var>.padStart(<var>targetLength</var> [, <var>padString</var>])</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>targetLength</code></dt> + <dd>목표 문자열 길이. 현재 문자열의 길이보다 작다면 채워넣지 않고 그대로 반환.</dd> + <dt><code>padString</code> {{optional_inline}}</dt> + <dd>현재 문자열에 채워넣을 다른 문자열. 문자열이 너무 길어 목표 문자열 길이를 초과한다면 좌측 일부를 잘라서 넣음. 기본값은 " ". (U+0020)</dd> +</dl> + +<h3 id="반환값">반환값</h3> + +<p>시작점부터 주어진 문자열로 채워 목표 길이를 만족하는 {{jsxref("String")}}.</p> + +<h2 id="예시">예시</h2> + +<pre class="brush: js">'abc'.padStart(10); // " abc" +'abc'.padStart(10, "foo"); // "foofoofabc" +'abc'.padStart(6,"123465"); // "123abc" +'abc'.padStart(8, "0"); // "00000abc" +'abc'.padStart(1); // "abc"</pre> + +<h2 id="폴리필">폴리필</h2> + +<p>다른 모든 코드 이전에 아래 코드를 포함하면 지원하지 않는 플랫폼에서도 <code>String.prototype.padStart()</code> 메서드를 사용할 수 있습니다.</p> + +<pre class="brush: js">// https://github.com/uxitten/polyfill/blob/master/string.polyfill.js +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart +if (!String.prototype.padStart) { + String.prototype.padStart = function padStart(targetLength,padString) { + targetLength = targetLength>>0; //truncate if number or convert non-number to 0; + padString = String((typeof padString !== 'undefined' ? padString : ' ')); + if (this.length > targetLength) { + return String(this); + } + else { + targetLength = targetLength-this.length; + if (targetLength > padString.length) { + padString += padString.repeat(targetLength/padString.length); //append to original to ensure we are longer than needed + } + return padString.slice(0,targetLength) + String(this); + } + }; +} +</pre> + +<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('ESDraft', '#sec-string.prototype.padstart', 'String.prototype.padStart')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Initial definition in ECMAScript 2017.</td> + </tr> + <tr> + <td>{{SpecName('ES8', '#sec-string.prototype.padstart', 'String.prototype.padStart')}}</td> + <td>{{Spec2('ES8')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.padStart")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("String.prototype.padEnd()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/prototype/index.html b/files/ko/web/javascript/reference/global_objects/string/prototype/index.html new file mode 100644 index 0000000000..707680d3c4 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/prototype/index.html @@ -0,0 +1,218 @@ +--- +title: String.prototype +slug: Web/JavaScript/Reference/Global_Objects/String/prototype +tags: + - JavaScript + - Property + - Prototype + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String +--- +<div>{{JSRef("Global_Objects", "String")}}</div> + +<h2 id="Summary" name="Summary">요약</h2> + +<p><strong><code>String.prototype</code></strong> 프라퍼티는 {{jsxref("Global_Objects/String", "String")}} 프로토타입 오브젝트를 표현하고 있습니다.</p> + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="Description" name="Description">설명</h2> + +<p>모든 {{jsxref("Global_Objects/String", "String")}} 인스턴스들은 <code>String.prototype</code>를 상속합니다. <code>String</code> 프라퍼티 오브젝트를 변경하면, 그 변경은 모든 {{jsxref("Global_Objects/String", "String")}} 인스턴스들에 영향을 주게 됩니다.</p> + +<h2 id="Properties" name="Properties">Properties</h2> + +<dl> + <dt><code>String.prototype.constructor</code></dt> + <dd>오브젝트의 프로토타입을 생성하는 함수를 명세합니다.</dd> + <dt>{{jsxref("String.prototype.length")}}</dt> + <dd>문자열의 길이를 반영합니다.</dd> + <dt><code><em>N</em></code></dt> + <dd><em>N</em>번째 위치에 있는 문자에 접근하기 위해 사용합니다. <em>N</em> 은 0과 {{jsxref("String.length", "length")}}보다 작은 값 사이에 있는 양의 정수입니다. 이 퍼라퍼티들은 읽기 전용(read-only) 속성을 가지고 있습니다. </dd> +</dl> + +<h2 id="Methods" name="Methods">메서드</h2> + +<h3 id="Methods_unrelated_to_HTML" name="Methods_unrelated_to_HTML">HTML과 관련이 없는 메서드</h3> + +<dl> + <dt>{{jsxref("String.prototype.charAt()")}}</dt> + <dd>문자열 내 특정 위치(index)에 있는 문자를 반환합니다.</dd> + <dt>{{jsxref("String.prototype.charCodeAt()")}}</dt> + <dd>문자열 내 주어진 위치(index)에 있는 문자의 유니코드 값을 반환합니다.</dd> + <dt>{{jsxref("String.prototype.codePointAt()")}} {{experimental_inline}}</dt> + <dd>주어진 위치에 있는 UTF-16으로 인코딩된 코드 포인터값인 음수가 아닌 정수값을 반환합니다. </dd> + <dt>{{jsxref("String.prototype.concat()")}}</dt> + <dd>두 문자열의 문자를 합쳐서 새로운 문자열로 만든 다음, 그 새로운 문자열을 반환합니다. </dd> + <dt>{{jsxref("String.prototype.includes()")}} {{experimental_inline}}</dt> + <dd>문자열 내에 찾고자 하는 문자열이 있는지를 확인합니다. </dd> + <dt>{{jsxref("String.prototype.endsWith()")}} {{experimental_inline}}</dt> + <dd>문자열에서 특정 문자열로 끝나는지를 확인할 수 있습니다.</dd> + <dt>{{jsxref("String.prototype.indexOf()")}}</dt> + <dd>{{jsxref("Global_Objects/String", "String")}} 오브젝트에 있는 특정 값이 일치하는 첫 번째 인덱스 값을 반환하며, 일치하는 값이 없을 경우에는 -1을 반환합니다.</dd> + <dt>{{jsxref("String.prototype.lastIndexOf()")}}</dt> + <dd><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String" title="String 글로벌 오브젝트는 문자열의 생성자, 또는 문자열의 순서입니다."><code>String</code></a> 오브젝트에서 <code>fromIndex</code>로부터 반대방향으로 찾기 시작하여 특정 값이 일치하는 마지막 인덱스를 반환합니다. 문자열에서 일치하는 특정 값이 없으면 <code>-1</code>을 리턴합니다.</dd> + <dt>{{jsxref("String.prototype.localeCompare()")}}</dt> + <dd>Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.</dd> + <dt>{{jsxref("String.prototype.match()")}}</dt> + <dd>Used to match a regular expression against a string.</dd> + <dt>{{jsxref("String.prototype.normalize()")}} {{experimental_inline}}</dt> + <dd>Returns the Unicode Normalization Form of the calling string value.</dd> + <dt><s class="obsoleteElement">{{jsxref("String.prototype.quote()")}} {{obsolete_inline}}</s></dt> + <dd><s class="obsoleteElement">Wraps the string in double quotes ("<code>"</code>").</s></dd> + <dt>{{jsxref("String.prototype.repeat()")}} {{experimental_inline}}</dt> + <dd>Returns a string consisting of the elements of the object repeated the given times.</dd> + <dt>{{jsxref("String.prototype.replace()")}}</dt> + <dd>Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring.</dd> + <dt>{{jsxref("String.prototype.search()")}}</dt> + <dd>Executes the search for a match between a regular expression and a specified string.</dd> + <dt>{{jsxref("String.prototype.slice()")}}</dt> + <dd>Extracts a section of a string and returns a new string.</dd> + <dt>{{jsxref("String.prototype.split()")}}</dt> + <dd>Splits a {{jsxref("Global_Objects/String", "String")}} object into an array of strings by separating the string into substrings.</dd> + <dt>{{jsxref("String.prototype.startsWith()")}} {{experimental_inline}}</dt> + <dd>Determines whether a string begins with the characters of another string.</dd> + <dt>{{jsxref("String.prototype.substr()")}}</dt> + <dd>Returns the characters in a string beginning at the specified location through the specified number of characters.</dd> + <dt>{{jsxref("String.prototype.substring()")}}</dt> + <dd>Returns the characters in a string between two indexes into the string.</dd> + <dt>{{jsxref("String.prototype.toLocaleLowerCase()")}}</dt> + <dd>The characters within a string are converted to lower case while respecting the current locale. For most languages, this will return the same as {{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}}.</dd> + <dt>{{jsxref("String.prototype.toLocaleUpperCase()")}}</dt> + <dd>The characters within a string are converted to upper case while respecting the current locale. For most languages, this will return the same as {{jsxref("String.prototype.toUpperCase()", "toUpperCase()")}}.</dd> + <dt>{{jsxref("String.prototype.toLowerCase()")}}</dt> + <dd>Returns the calling string value converted to lower case.</dd> + <dt>{{jsxref("String.prototype.toSource()")}} {{non-standard_inline}}</dt> + <dd>Returns an object literal representing the specified object; you can use this value to create a new object. Overrides the {{jsxref("Object.prototype.toSource()")}} method.</dd> + <dt>{{jsxref("String.prototype.toString()")}}</dt> + <dd>Returns a string representing the specified object. Overrides the {{jsxref("Object.prototype.toString()")}} method.</dd> + <dt>{{jsxref("String.prototype.toUpperCase()")}}</dt> + <dd>Returns the calling string value converted to uppercase.</dd> + <dt>{{jsxref("String.prototype.trim()")}}</dt> + <dd>Trims whitespace from the beginning and end of the string. Part of the ECMAScript 5 standard.</dd> + <dt>{{jsxref("String.prototype.trimLeft()")}} {{non-standard_inline}}</dt> + <dd>Trims whitespace from the left side of the string.</dd> + <dt>{{jsxref("String.prototype.trimRight()")}} {{non-standard_inline}}</dt> + <dd>Trims whitespace from the right side of the string.</dd> + <dt>{{jsxref("String.prototype.valueOf()")}}</dt> + <dd>Returns the primitive value of the specified object. Overrides the {{jsxref("Object.prototype.valueOf()")}} method.</dd> + <dt>{{jsxref("String.prototype.@@iterator()", "String.prototype[@@iterator]()")}} {{experimental_inline}}</dt> + <dd>Returns a new <code>Iterator</code> object that iterates over the code points of a String value, returning each code point as a String value.</dd> +</dl> + +<h3 id="HTML_wrapper_methods" name="HTML_wrapper_methods">HTML wrapper methods</h3> + +<p>These methods are of limited use, as they provide only a subset of the available HTML tags and attributes.</p> + +<dl> + <dt>{{jsxref("String.prototype.big()")}} {{deprecated_inline}}</dt> + <dd>{{HTMLElement("big")}}</dd> + <dt>{{jsxref("String.prototype.blink()")}} {{deprecated_inline}}</dt> + <dd>{{HTMLElement("blink")}}</dd> + <dt>{{jsxref("String.prototype.bold()")}} {{deprecated_inline}}</dt> + <dd>{{HTMLElement("b")}}</dd> + <dt>{{jsxref("String.prototype.fixed()")}} {{deprecated_inline}}</dt> + <dd>{{HTMLElement("tt")}}</dd> + <dt>{{jsxref("String.prototype.fontcolor()")}} {{deprecated_inline}}</dt> + <dd>{{htmlattrxref("color", "font", "<font color=\"color\">")}}</dd> + <dt>{{jsxref("String.prototype.fontsize()")}} {{deprecated_inline}}</dt> + <dd>{{htmlattrxref("size", "font", "<font size=\"size\">")}}</dd> + <dt>{{jsxref("String.prototype.italics()")}} {{deprecated_inline}}</dt> + <dd>{{HTMLElement("i")}}</dd> + <dt>{{jsxref("String.prototype.link()")}}</dt> + <dd>{{htmlattrxref("href", "a", "<a href=\"rul\">")}} (link to URL)</dd> + <dt>{{jsxref("String.prototype.small()")}} {{deprecated_inline}}</dt> + <dd>{{HTMLElement("small")}}</dd> + <dt>{{jsxref("String.prototype.strike()")}} {{deprecated_inline}}</dt> + <dd>{{HTMLElement("strike")}}</dd> + <dt>{{jsxref("String.prototype.sub()")}} {{deprecated_inline}}</dt> + <dd>{{HTMLElement("sub")}}</dd> + <dt>{{jsxref("String.prototype.sup()")}} {{deprecated_inline}}</dt> + <dd>{{HTMLElement("sup")}}</dd> +</dl> + +<h2 id="Specifications">Specifications</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>ECMAScript 1st Edition.</td> + <td>Standard</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.3.1', 'String.prototype')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype', 'String.prototype')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also" name="See_also">See also</h2> + +<ul> + <li>{{jsxref("Global_Objects/String", "String")}}</li> + <li>{{jsxref("Function.prototype")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/repeat/index.html b/files/ko/web/javascript/reference/global_objects/string/repeat/index.html new file mode 100644 index 0000000000..8e1d67988b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/repeat/index.html @@ -0,0 +1,113 @@ +--- +title: String.prototype.repeat() +slug: Web/JavaScript/Reference/Global_Objects/String/repeat +translation_of: Web/JavaScript/Reference/Global_Objects/String/repeat +--- +<div>{{JSRef}}</div> + +<p><strong><code>repeat()</code></strong> 메서드는 문자열을 주어진 횟수만큼 반복해 붙인 새로운 문자열을 반환합니다.</p> + +<h2 id="구문">구문</h2> + +<pre><code><var>str</var>.repeat(<var>count</var>);</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>count</code></dt> + <dd>문자열을 반복할 횟수. 0과 양의 무한대 사이의 정수([0, +∞)).</dd> +</dl> + +<h3 id="반환값">반환값</h3> + +<p>현재 문자열을 주어진 횟수만큼 반복해 붙인 새로운 문자열.</p> + +<h3 id="예외">예외</h3> + +<ul> + <li>{{jsxref("Errors/Negative_repetition_count", "RangeError")}}: 반복 횟수는 양의 정수여야 함.</li> + <li>{{jsxref("Errors/Resulting_string_too_large", "RangeError")}}: 반복 횟수는 무한대보다 작아야 하며, 최대 문자열 크기를 넘어선 안됨.</li> +</ul> + +<h2 id="예제">예제</h2> + +<pre class="brush: js">'abc'.repeat(-1); // RangeError +'abc'.repeat(0); // '' +'abc'.repeat(1); // 'abc' +'abc'.repeat(2); // 'abcabc' +'abc'.repeat(3.5); // 'abcabcabc' (count will be converted to integer) +'abc'.repeat(1/0); // RangeError + +({ toString: () => 'abc', repeat: String.prototype.repeat }).repeat(2); +// 'abcabc' (repeat() is a generic method) +</pre> + +<h2 id="폴리필">폴리필</h2> + +<p><code>repeat</code>은 ECMAScript 2015 명세에 추가됐습니다. 따라서 어떤 표준 구현체에서는 사용할 수 없을 수도 있습니다. 그러나 아래 코드를 포함하면 지원하지 않는 플랫폼에서도 <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">repeat</span></font>을 사용할 수 있습니다.</p> + +<pre dir="rtl"><code>if (!String.prototype.repeat) { + String.prototype.repeat = function(count) { + 'use strict'; + if (this == null) { + throw new TypeError('can\'t convert ' + this + ' to object'); + } + var str = '' + this; + count = +count; + if (count != count) { + count = 0; + } + if (count < 0) { + throw new RangeError('repeat count must be non-negative'); + } + if (count == Infinity) { + throw new RangeError('repeat count must be less than infinity'); + } + count = Math.floor(count); + if (str.length == 0 || count == 0) { + return ''; + } + // Ensuring count is a 31-bit integer allows us to heavily optimize the + // main part. But anyway, most current (August 2014) browsers can't handle + // strings 1 << 28 chars or longer, so: + if (str.length * count >= 1 << 28) { + throw new RangeError('repeat count must not overflow maximum string size'); + } + var maxCount = str.length * count; + count = Math.floor(Math.log(count) / Math.log(2)); + while (count) { + str += str; + count--; + } + str += str.substring(0, maxCount - str.length); + return str; + } +}</code></pre> + +<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('ES2015', '#sec-string.prototype.repeat', 'String.prototype.repeat')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.repeat', 'String.prototype.repeat')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.repeat")}}</p> 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>$&</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>$& </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, '-' + '$&'.toLowerCase()); // won't work +</pre> + +<p>This is because <code>'$&'.toLowerCase()</code> would be evaluated first as a string literal (resulting in the same <code>'$&'</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> diff --git a/files/ko/web/javascript/reference/global_objects/string/search/index.html b/files/ko/web/javascript/reference/global_objects/string/search/index.html new file mode 100644 index 0000000000..3d27d812fc --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/search/index.html @@ -0,0 +1,100 @@ +--- +title: String.prototype.search() +slug: Web/JavaScript/Reference/Global_Objects/String/search +translation_of: Web/JavaScript/Reference/Global_Objects/String/search +--- +<div>{{JSRef}}</div> + +<p><strong><code>search()</code></strong> 메서드는 정규 표현식과 이 {{jsxref("String")}} 객체간에 같은 것을 찾기<br> + 위한 검색을 실행한다.</p> + +<div>{{EmbedInteractiveExample("pages/js/string-search.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>str</var>.search(<var>regexp</var>)</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>regexp</code></dt> + <dd>정규 표현식 객체. non-RegExp 객체 <code>obj</code> 가 전달되면, 그것은 <code>new RegExp(obj)</code> 을 이용하여 {{jsxref("RegExp")}} 으로 암묵적으로 변환된다.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>정규표현식과 주어진 스트링간에 첫번째로 매치되는 것의 인덱스를 반환한다.<br> + 찾지 못하면 <strong>-1</strong> 를 반환한다.</p> + +<h2 id="설명">설명</h2> + +<p>When you want to know whether a pattern is found and also its index in a string use <code>search()</code> (if you only want to know if it exists, use the similar {{jsxref("RegExp.prototype.test()", "test()")}} method on the RegExp prototype, which returns a boolean); for more information (but slower execution) use {{jsxref("String.prototype.match()", "match()")}} (similar to the regular expression {{jsxref("RegExp.prototype.exec()", "exec()")}} method).</p> + +<h2 id="예">예</h2> + +<h3 id="search()를_이용하기"><code>search()를 이용하기</code></h3> + +<p>The following example searches a string with 2 different regex objects to show a successful search (positive value) vs. an unsuccessful search (-1)</p> + +<pre class="brush: js">var str = "hey JudE"; +var re = /[A-Z]/g; +var re2 = /[.]/g; +console.log(str.search(re)); // returns 4, which is the index of the first capital letter "J" +console.log(str.search(re2)); // returns -1 cannot find '.' dot punctuation</pre> + +<h2 id="사양">사양</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">사양</th> + <th scope="col">상태</th> + <th scope="col">주석</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.12', 'String.prototype.search')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.search', 'String.prototype.search')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.search', 'String.prototype.search')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.search")}}</p> + +<h2 id="Gecko-specific_notes">Gecko-specific notes</h2> + +<ul> + <li><code>flags</code> was a non standard second argument only available in Gecko : <var>str</var>.search(<var>regexp, flags</var>)</li> + <li>Prior to {{Gecko("8.0")}}, <code>search()</code> was implemented incorrectly; when it was called with no parameters or with {{jsxref("undefined")}}, it would match against the string 'undefined', instead of matching against the empty string. This is fixed; now <code>'a'.search()</code> and <code>'a'.search(undefined)</code> correctly return 0.</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="See_also">See also</h2> + +<ul> + <li>{{jsxref("String.prototype.match()")}}</li> + <li>{{jsxref("RegExp.prototype.exec()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/slice/index.html b/files/ko/web/javascript/reference/global_objects/string/slice/index.html new file mode 100644 index 0000000000..3bd23ace3b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/slice/index.html @@ -0,0 +1,129 @@ +--- +title: String.prototype.slice() +slug: Web/JavaScript/Reference/Global_Objects/String/slice +tags: + - 메소드 + - 문자열 + - 자바스크립트 + - 프로토타입 +translation_of: Web/JavaScript/Reference/Global_Objects/String/slice +--- +<div>{{JSRef}}</div> + +<p><strong><code>slice()</code></strong> 메소드는 문자열의 일부를 추출하면서 새로운 문자열을 반환합니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/string-slice.html")}}</p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox notranslate"><code><var>str</var>.slice(<var>beginIndex</var>[, <var>endIndex</var>])</code></pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>beginIndex</code></dt> + <dd>추출 시작점인 0부터 시작하는 인덱스입니다. 만약 음수라면, beginIndex는 <code>strLength(문자열 길이) + beginIndex</code>로 취급됩니다. (예를 들어 <code>beginIndex</code>가 -3이면 시작점은 <code>strLength - 3</code>).</dd> + <dd>만약 <code>beginIndex</code>가 <code>strLength</code> 보다 크거나 같은 경우, <code>slice()</code>는 빈 문자열을 반환합니다.</dd> + <dt><code>endIndex</code>{{optional_inline}}</dt> + <dd>0부터 시작하는 추출 종료점 인덱스로 그 직전까지 추출됩니다. 인덱스 위치의 문자는 추출에 포함되지 않습니다.</dd> + <dd>만약 <code>endIndex</code>가 생략된다면, <code>silce()</code>는 문자열 마지막까지 추출합니다. 만약 음수라면, endIndex는 <code>strLength(문자열 길이) + endIndex</code> 로 취급됩니다(예를 들어 <code>endIndex</code>가 -3이면 종료점은 <code>strLength - 3</code>).</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>문자열의 추출된 부분을 담는 새로운 문자열이 반환됩니다.</p> + +<h2 id="설명">설명</h2> + +<p><code>slice()</code>는 문자열로부터 텍스트를 추출하고 새 문자열을 반환합니다. 문자열의 변경은 다른 문자열에 영향을 미치지 않습니다.</p> + +<p><code>slice()</code>는 <code>endIndex</code>를 포함하지 않고 추출합니다. <code>str.slice(1, 4)</code>는 두 번째 문자부터 네 번째 문자까지 추출합니다 (1, 2, 3 인덱스 문자).</p> + +<p><code>str.slice(2, -1)</code>는 세 번째 문자부터 문자열의 마지막에서 두 번째 문자까지 추출합니다.</p> + +<h2 id="예시">예시</h2> + +<h3 id="slice를_사용하여_새_문자열_생성하기"><code>slice()</code>를 사용하여 새 문자열 생성하기</h3> + +<p>아래 예시는 새 문자열을 생성하기 위해 <code>slice()</code>를 사용합니다.</p> + +<pre class="brush: js notranslate">var str1 = 'The morning is upon us.', // the length of str1 is 23. + str2 = str1.slice(1, 8), + str3 = str1.slice(4, -2), + str4 = str1.slice(12), + str5 = str1.slice(30); +console.log(str2); // OUTPUT: he morn +console.log(str3); // OUTPUT: morning is upon u +console.log(str4); // OUTPUT: is upon us. +console.log(str5); // OUTPUT: "" +</pre> + +<h3 id="음수_인덱스로_slice_사용하기">음수 인덱스로 <code>slice()</code> 사용하기</h3> + +<p>아래 예시는 <code>slice()</code>에 음수 인덱스를 사용합니다.</p> + +<pre class="brush: js notranslate">var str = 'The morning is upon us.'; +str.slice(-3); // returns 'us.' +str.slice(-3, -1); // returns 'us' +str.slice(0, -1); // returns 'The morning is upon us' +</pre> + +<p>아래의 예시는 시작 인덱스를 찾기 위해 문자열의 끝에서부터 역방향으로 <code>11</code>개를 세고 끝 인덱스를 찾기 위해 문자열의 시작에서부터 정방향으로 <code>16</code>개를 셉니다.</p> + +<pre class="brush: js notranslate"><code>console.log(str.slice(-11, 16)) // => "is u";</code></pre> + +<p>아래에서는 시작 인덱스를 찾기 위해 문자열의 처음부터 정방향으로 <code>11</code>개를 세고 끝 인덱스를 찾기 위해 끝에서부터 <code>7</code>개를 셉니다.</p> + +<pre class="brush: js notranslate"><code>console.log(str.slice(11, -7)) // => "is u";</code> +</pre> + +<p>이 인수는 끝에서부터 5로 역순으로 계산하여 시작 인덱스를 찾은 다음 끝에서부터 1을 거쳐 끝 인덱스를 찾습니다.</p> + +<pre class="brush: js notranslate"><code>console.log(str.slice(-5, -1)) // => "n us";</code> +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.slice', 'String.prototype.slice')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.slice', 'String.prototype.slice')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.13', 'String.prototype.slice')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.2.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>{{Compat("javascript.builtins.String.slice")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("String.prototype.substr()")}}</li> + <li>{{jsxref("String.prototype.substring()")}}</li> + <li>{{jsxref("Array.prototype.slice()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/split/index.html b/files/ko/web/javascript/reference/global_objects/string/split/index.html new file mode 100644 index 0000000000..7100e55a50 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/split/index.html @@ -0,0 +1,231 @@ +--- +title: String.prototype.split() +slug: Web/JavaScript/Reference/Global_Objects/String/split +tags: + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/split +--- +<div>{{JSRef}}</div> + +<p><strong><code>split()</code></strong> 메서드는 {{jsxref("String")}} 객체를 지정한 구분자를 이용하여 여러 개의 문자열로 나눕니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/string-split.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>str</var>.split([<var>separator</var>[, <var>limit</var>]])</pre> + +<div class="warning"> +<p><strong>주의:</strong> 구분자로 빈 문자열(<code>""</code>)을 제공하면, 사용자가 인식하는 문자 하나(<a href="https://unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries">grapheme cluster</a>) 또는 유니코드 문자(코드포인트) 하나씩으로 나누는 것이 아니라, UTF-16 코드유닛으로 나누게 되며 <a href="http://unicode.org/faq/utf_bom.html#utf16-2">써로게이트 페어</a><sup>surrogate pair</sup>가 망가질 수 있습니다. 스택 오버플로우의 <a href="https://stackoverflow.com/a/34717402">How do you get a string to a character array in JavaScript?</a> 질문도 참고해 보세요.</p> +</div> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>separator</code> {{optional_inline}}</dt> + <dd>원본 문자열을 끊어야 할 부분을 나타내는 문자열을 나타냅니다. 실제 문자열이나 {{jsxref("Global_Objects/RegExp", "정규표현식", "", 1)}}을 받을 수 있습니다. 문자열 유형의 <code>separator</code>가 두 글자 이상일 경우 그 부분 문자열 전체가 일치해야 끊어집니다. <code>separator</code>가 생략되거나 <code>str</code>에 등장하지 않을 경우, 반환되는 배열은 원본 문자열을 유일한 원소로 가집니다. <code>separator</code>가 빈 문자열일 경우 <code>str</code>의 각각의 문자가 배열의 원소 하나씩으로 변환됩니다.</dd> + <dt><code>limit</code> {{optional_inline}}</dt> + <dd> + <p>끊어진 문자열의 최대 개수를 나타내는 정수입니다. 이 매개변수를 전달하면 split() 메서드는 주어진 <code>separator</code>가 등장할 때마다 문자열을 끊지만 배열의 원소가 <code>limit</code>개가 되면 멈춥니다. 지정된 한계에 도달하기 전에 문자열의 끝까지 탐색했을 경우 <code>limit</code>개 미만의 원소가 있을 수도 있습니다. 남은 문자열은 새로운 배열에 포함되지 않습니다.</p> + </dd> +</dl> + +<h3 id="반환값">반환값</h3> + +<p>주어진 문자열을 <code>separator</code>마다 끊은 부분 문자열을 담은 {{jsxref("Array")}}.</p> + +<h2 id="설명">설명</h2> + +<p>문자열에서 <code>separator</code>가 등장하면 해당 부분은 삭제되고 남은 문자열이 배열로 반환됩니다. <code>separator</code>가 등장하지 않거나 생략되었을 경우 배열은 원본 문자열을 유일한 원소로 가집니다. <code>separator</code>가 빈 문자열일 경우, <code>str</code>은 문자열의 모든 문자를 원소로 가지는 배열로 변환됩니다. <code>separator</code>가 원본 문자열의 처음이나 끝에 등장할 경우 반환되는 배열도 빈 문자열로 시작하거나 끝납니다. 그러므로 원본 문자열에 <code>separator</code> 하나만이 포함되어 있을 경우 빈 문자열 두 개를 원소로 가지는 배열이 반환됩니다.</p> + +<p><code>separator</code>가 포획 괄호<sup>capturing parentheses</sup>를 포함하는 정규표현식일 경우, <code>separator</code>가 일치할 때마다 포획 괄호의 (정의되지 않은 경우도 포함한) 결과가 배열의 해당 위치에 포함됩니다.</p> + +<p>{{Note("<code>separator</code>가 배열일 경우 분할에 사용하기 전에 우선 문자열로 변환됩니다.")}}</p> + +<h2 id="예제">예제</h2> + +<h3 id="split()_사용하기"><code>split()</code> 사용하기</h3> + +<p>{{Note("빈 문자열이 주어졌을 경우 <code>split()</code>은 빈 배열이 아니라 빈 문자열을 포함한 배열을 반환합니다. 문자열과 <code>separator</code>가 모두 빈 문자열일 때는 빈 배열을 반환합니다.")}}</p> + +<pre class="brush: js">const myString = ''; +const splits = myString.split(); + +console.log(splits); + +// ↪ [""] +</pre> + +<p>다음 예제에서는 문자열을 주어진 구분자로 끊는 함수를 정의합니다. 문자열을 끊은 다음에는 (끊기 이전의) 원본 문자열과 사용한 구분자, 배열의 길이와 각 원소를 로그로 출력합니다.</p> + +<pre class="brush: js">function splitString(stringToSplit, separator) { + var arrayOfStrings = stringToSplit.split(separator); + + console.log('The original string is: "' + stringToSplit + '"'); + console.log('The separator is: "' + separator + '"'); + console.log('The array has ' + arrayOfStrings.length + ' elements: ' + arrayOfStrings.join(' / ')); +} + +var tempestString = 'Oh brave new world that has such people in it.'; +var monthString = 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'; + +var space = ' '; +var comma = ','; + +splitString(tempestString, space); +splitString(tempestString); +splitString(monthString, comma); +</pre> + +<p>위 예제의 출력은 다음과 같습니다.</p> + +<pre>The original string is: "Oh brave new world that has such people in it." +The separator is: " " +The array has 10 elements: Oh / brave / new / world / that / has / such / people / in / it. + +The original string is: "Oh brave new world that has such people in it." +The separator is: "undefined" +The array has 1 elements: Oh brave new world that has such people in it. + +The original string is: "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec" +The separator is: "," +The array has 12 elements: Jan / Feb / Mar / Apr / May / Jun / Jul / Aug / Sep / Oct / Nov / Dec +</pre> + +<h3 id="문자열에서_공백_제거하기">문자열에서 공백 제거하기</h3> + +<p>다음 예제에서 <code>split()</code>은 세미콜론 앞뒤에 각각 0개 이상의 공백이 있는 부분 문자열을 찾고, 있을 경우 문자열에서 세미콜론과 공백을 제거합니다. <code>split()</code>의 결과로 반환된 배열은 <code>nameList</code>에 저장됩니다.</p> + +<pre class="brush: js">var names = 'Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand '; + +console.log(names); + +var re = /\s*(?:;|$)\s*/; +var nameList = names.split(re); + +console.log(nameList); +</pre> + +<p>위 예제는 원본 문자열과 반환된 배열을 각각 한 줄씩 로그로 출력합니다.</p> + +<pre>Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand +[ "Harry Trump", "Fred Barney", "Helen Rigby", "Bill Abel", "Chris Hand", "" ] +</pre> + +<h3 id="끊는_횟수_제한하기">끊는 횟수 제한하기</h3> + +<p>다음 예제에서 <code>split()</code>은 문자열을 공백으로 끊고 처음 3개의 문자열을 반환합니다.</p> + +<pre class="brush: js">var myString = 'Hello World. How are you doing?'; +var splits = myString.split(' ', 3); + +console.log(splits); +</pre> + +<p>위 예제의 로그 출력은 다음과 같습니다.</p> + +<pre>["Hello", "World.", "How"] +</pre> + +<h3 id="RegExp를_사용해_구분자도_결과에_포함하기"><code>RegExp</code>를 사용해 구분자도 결과에 포함하기</h3> + +<p><code>separator</code>가 포획 괄호 <code>()</code>를 포함하는 정규표현식일 경우, 포획된 결과도 배열에 포함됩니다.</p> + +<pre class="brush: js">var myString = 'Hello 1 word. Sentence number 2.'; +var splits = myString.split(/(\d)/); + +console.log(splits); +</pre> + +<p>위 예제의 로그 출력은 다음과 같습니다.</p> + +<pre>[ "Hello ", "1", " word. Sentence number ", "2", "." ] +</pre> + +<h3 id="배열을_구분자로_사용하기">배열을 구분자로 사용하기</h3> + +<pre class="brush: js">var myString = 'this|is|a|Test'; +var splits = myString.split(['|']); + +console.log(splits); //["this", "is", "a", "Test"] + +var myString = 'ca,bc,a,bca,bca,bc'; + +var splits = myString.split(['a','b']); +// <em>myString.split(['a','b'])</em>은 <em>myString.split(String(['a','b']))</em>와 같다 + +console.log(splits); //["c", "c,", "c", "c", "c"] +</pre> + +<h3 id="split()으로_문자열_뒤집기"><code>split()</code>으로 문자열 뒤집기</h3> + +<div class="warning"> +<p>이 방법은 문자열 뒤집기에 효과적인 방법이 아닙니다.</p> + +<pre class="brush: js">var str = 'asdfghjkl'; +var strReverse = str.split('').reverse().join(''); // 'lkjhgfdsa' +// split()에서 반환한 배열에는 reverse()와 join()을 사용할 수 있다 +</pre> + +<p>문자열에 grapheme clusters가 있을 경우, 유니코드 플래그를 설정해도 오류를 일으킵니다(<a href="https://github.com/mathiasbynens/esrever">esrever</a> 등의 라이브러리를 대신 사용하세요).</p> + +<pre class="brush: js">var str = 'résumé'; +var strReverse = str.split(/(?:)/u).reverse().join(''); +// => "́emuśer" +</pre> + +<p><strong>추가:</strong> {{jsxref("Operators/Comparison_Operators", "===", "#Identity_strict_equality_(===)")}} 연산자를 사용하면 원본 문자열이 팰린드롬인지 확인할 수 있습니다.</p> +</div> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">비고</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>초기 정의. JavaScript 1.1에 구현되었음.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.14', 'String.prototype.split')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.split', 'String.prototype.split')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.split', 'String.prototype.split')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.split")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("String.prototype.charAt()")}}</li> + <li>{{jsxref("String.prototype.indexOf()")}}</li> + <li>{{jsxref("String.prototype.lastIndexOf()")}}</li> + <li>{{jsxref("Array.prototype.join()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/startswith/index.html b/files/ko/web/javascript/reference/global_objects/string/startswith/index.html new file mode 100644 index 0000000000..41eb064129 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/startswith/index.html @@ -0,0 +1,95 @@ +--- +title: String.prototype.startsWith() +slug: Web/JavaScript/Reference/Global_Objects/String/startsWith +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/startsWith +--- +<div>{{JSRef}}</div> + +<p><span class="seoSummary"><strong><code>startsWith()</code></strong></span><span class="seoSummary"> 메소드는 어떤 문자열이 특정 문자로 시작하는지 확인하여 결과를 <code>true</code> 혹은 <code>false</code>로 반환합니다.</span></p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>str</var>.startsWith(<var>searchString</var>[, <var>position</var>])</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>searchString</code></dt> + <dd>문자열의 시작 지점에서 탐색할 문자열</dd> + <dt><code>position</code> {{optional_inline}}</dt> + <dd><code>searchString</code>을 탐색할 위치. 기본값 0.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>문자열이 검색 문자열로 시작하면 <code>true</code>, 아니면 <code>false</code>.</p> + +<h2 id="설명"><span style="display: none;"> </span><span style="display: none;"> </span>설명</h2> + +<p><code>startsWith</code> 메소드로 어떤 문자열이 다른 문자열로 시작하는지 확인 할 수 있습니다. 대소문자를 구분합니다.</p> + +<h2 id="예시">예시</h2> + +<h3 id="startsWith()_사용하기"><code>startsWith()</code> 사용하기</h3> + +<pre class="brush: js">//startswith +var str = 'To be, or not to be, that is the question.'; + +console.log(str.startsWith('To be')); // true +console.log(str.startsWith('not to be')); // false +console.log(str.startsWith('not to be', 10)); // true +</pre> + +<h2 id="폴리필">폴리필</h2> + +<p><code>startsWith</code> 메소드는 ECMAScript 2015 명세에 포함됐으며, 아직까지 모든 JavaScrpt 구현체가 지원하지 않을 수 있습니다. 그러나 아래 코드 조각을 사용해 폴리필 할 수 있습니다.</p> + +<pre><code>if (!String.prototype.startsWith) { + String.prototype.startsWith = function(search, pos) { + return this.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; + }; +}</code></pre> + +<p>ES2015 명세를 모두 만족하지만, 더 무거운 폴리필은 <a href="https://github.com/mathiasbynens/String.prototype.startsWith">Mathias Bynens의 GitHub</a> 에서 확인할 수 있습니다.</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('ES6', '#sec-string.prototype.startswith', 'String.prototype.startsWith')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.startswith', 'String.prototype.startsWith')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{Compat("javascript.builtins.String.startsWith")}}</div> + +<h2 id="관련_문서">관련 문서</h2> + +<ul> + <li>{{jsxref("String.prototype.endsWith()")}}</li> + <li>{{jsxref("String.prototype.includes()")}}</li> + <li>{{jsxref("String.prototype.indexOf()")}}</li> + <li>{{jsxref("String.prototype.lastIndexOf()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/substr/index.html b/files/ko/web/javascript/reference/global_objects/string/substr/index.html new file mode 100644 index 0000000000..39fe5e126b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/substr/index.html @@ -0,0 +1,131 @@ +--- +title: String.prototype.substr() +slug: Web/JavaScript/Reference/Global_Objects/String/substr +tags: + - Deprecated + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/substr +--- +<div>{{JSRef}}</div> + +<div> </div> + +<div class="warning"> +<p>경고: 엄밀히 말해서 <code>String.prototype.substr()</code> 메서드가 더 이상 사용되지 않는, 즉 "웹 표준에서 제거된" 건 아닙니다. 그러나 <code>substr()</code>이 포함된 ECMA-262 표준의 <a href="https://www.ecma-international.org/ecma-262/9.0/index.html#sec-additional-ecmascript-features-for-web-browsers">부록 B</a>는 다음과 같이 명시하고 있습니다.</p> + +<blockquote>… 본 부록이 포함한 모든 언어 기능과 행동은 하나 이상의 바람직하지 않은 특징을 갖고 있으며 사용처가 없어질 경우 명세에서 제거될 것입니다. …<br> +… 프로그래머는 새로운 ECMAScript 코드를 작성할 때 본 부록이 포함한 기능을 사용하거나 존재함을 가정해선 안됩니다. …</blockquote> +</div> + +<p><strong><code>substr()</code></strong> 메서드는 문자열에서 특정 위치에서 시작하여 특정 문자 수 만큼의 문자들을 반환합니다.</p> + +<p>{{EmbedInteractiveExample("pages/js/string-substr.html")}}</p> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>str</var>.substr(<var>start</var>[, <var>length</var>])</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>start</code></dt> + <dd>추출하고자 하는 문자들의 시작위치입니다. 만약 음수가 주어진다면, <code>문자열총길이 + start</code>의 값으로 취급합니다. 예를 들면, <code>start</code>에 -3을 설정하면, 자동적으로 <code>문자열총길이 - 3</code>으로 설정하게 됩니다. </dd> + <dt><code>length</code></dt> + <dd>옵션값. 추출할 문자들의 총 숫자.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p><code>start</code>는 문자 인덱스입니다. 문자열에서 첫 번째 문자의 인덱스는 0이며, 마지막 문자의 인덱스는 문자열 전체 길이에서 1을 뺀 값입니다. <code>substr()</code>는<code> start</code>에서 문자들을 추출을 시작하여 <code>length</code>만큼 문자들을 수집합니다.</p> + +<p>만약 <code>start</code> 값이 양수이고 문자열 전체 길이보다 크거가 같을 경우, <code>substr()</code>은 빈 문자열을 반환합니다. </p> + +<p>만약 <code>start</code>가 음수이면, <code>substr()</code>은 문자열 끝에서 <code>start</code> 숫자만큼 뺀 곳에서 시작하게 됩니다. 만약 <code>start</code>가 음수이고 절대값이 문자열 전체보다 크다면, <code>substr()</code>은 문자열의 0 인덱스부터 시작하게 됩니다. (주의: <code>start</code>의 음수값은 Microsoft JScript에서는 위의 설명과 같이 동작하지 않습니다.)</p> + +<p>만약 <code>length</code>가 0 혹은 음수이면, <code>substr()</code>은 빈 문자열을 반환합니다. 만약 <code>length</code>가 생략되면, <code>substr()</code>은 문자열의 끝까지 추출하여 반환합니다. </p> + +<h2 id="예제">예제</h2> + +<h3 id="substr()_사용하기"><code>substr()</code> 사용하기</h3> + +<pre class="brush: js">var str = 'abcdefghij'; + +console.log('(1, 2): ' + str.substr(1, 2)); // '(1, 2): bc' +console.log('(-3, 2): ' + str.substr(-3, 2)); // '(-3, 2): hi' +console.log('(-3): ' + str.substr(-3)); // '(-3): hij' +console.log('(1): ' + str.substr(1)); // '(1): bcdefghij' +console.log('(-20, 2): ' + str.substr(-20, 2)); // '(-20, 2): ab' +console.log('(20, 2): ' + str.substr(20, 2)); // '(20, 2): ' +</pre> + +<h2 id="폴리필">폴리필</h2> + +<p>Microsoft의 JScript는 시작 인덱스에서 음수값을 지원하지 않습니다. 만약 여러분이 이렇게 동작하길 원한다면, 아래 코드를 사용하여 해결할 수 있습니다: </p> + +<pre class="brush: js">// only run when the substr() function is broken +if ('ab'.substr(-1) != 'b') { + /** + * Get the substring of a string + * @param {integer} start where to start the substring + * @param {integer} length how many characters to return + * @return {string} + */ + String.prototype.substr = function(substr) { + return function(start, length) { + // call the original method + return substr.call(this, + // did we get a negative start, calculate how much it is from the beginning of the string + // adjust the start parameter for negative value + start < 0 ? this.length + start : start, + length) + } + }(String.prototype.substr); +} +</pre> + +<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>Defined in the (informative) Compatibility Annex B. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-B.2.3', 'String.prototype.substr')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Defined in the (informative) Compatibility Annex B</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.substr', 'String.prototype.substr')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.substr', 'String.prototype.substr')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div>{{Compat("javascript.builtins.String.substr")}}</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("String.prototype.slice()")}}</li> + <li>{{jsxref("String.prototype.substring()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/substring/index.html b/files/ko/web/javascript/reference/global_objects/string/substring/index.html new file mode 100644 index 0000000000..91d13974c9 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/substring/index.html @@ -0,0 +1,190 @@ +--- +title: String.prototype.substring() +slug: Web/JavaScript/Reference/Global_Objects/String/substring +translation_of: Web/JavaScript/Reference/Global_Objects/String/substring +--- +<div>{{JSRef}}</div> + +<p><strong><code>substring()</code></strong><font><font>메소드는 string 객체의 시작 인덱스로 부터 종료 인덱스 전 까지 문자열의 부분 문자열을 반환합니다. </font></font></p> + +<div>{{EmbedInteractiveExample("pages/js/string-substring.html")}}</div> + + + +<h2 id="사용방법">사용방법 </h2> + +<pre class="syntaxbox"><code><var>str</var>.substring(<var>indexStart</var>[, <var>indexEnd</var>])</code></pre> + +<h3 id="인자값">인자값</h3> + +<dl> + <dt><code><var>indexStart</var></code></dt> + <dd>반환문자열의 시작 인덱스 </dd> + <dt> </dt> + <dt><code><var>indexEnd</var></code></dt> + <dd>옵션. 반환문자열의 마지막 인덱스 (포함하지 않음.)</dd> +</dl> + +<h3 id="반환값">반환값</h3> + +<p>기존문자열의 부분 문자열을 반환합니다. </p> + +<h2 id="Description">Description</h2> + +<p><code>substring()</code> 메서드는 <code><var>indexStart</var></code> 부터 문자를 추출하지만 <code><var>indexEnd</var></code> 가 포함되지 않아도 괜찮습니다. 특징은 아래와 같습니다.</p> + +<ul> + <li>만약 <code><var>indexEnd</var></code> 가 생략된 경우, <code>substring()</code> 문자열의 끝까지 모든 문자를 추출합니다.</li> + <li>만약 <code><var>indexStart</var></code> 가 <code><var>indexEnd</var></code>와 같을 경우, <code>substring()</code> 빈 문자열을 반환합니다.</li> + <li>만약 <code><var>indexStart</var></code> 가 <code><var>indexEnd</var></code>보다 큰 경우, <code>substring()</code> 메서드는 마치 두 개의 인자를 바꾼 듯 작동하게 됩니다. 아래 예제를 보세요.</li> +</ul> + +<p>0보다 작은 인자 값을 가지는 경우에는 0으로, <code>stringName.length</code> 보다 큰 인자 값을 가지는 경우, <code>stringName.length</code> 로 처리됩니다. {{jsxref("NaN")}} 값은 0으로 처리됩니다.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_substring()">Using <code>substring()</code></h3> + +<p>The following example uses <code>substring()</code> to display characters from the string <code>'Mozilla'</code>:</p> + +<pre class="brush: js">var anyString = 'Mozilla'; + +// Displays 'M' +console.log(anyString.substring(0, 1)); +console.log(anyString.substring(1, 0)); + +// Displays 'Mozill' +console.log(anyString.substring(0, 6)); + +// Displays 'lla' +console.log(anyString.substring(4)); +console.log(anyString.substring(4, 7)); +console.log(anyString.substring(7, 4)); + +// Displays 'Mozilla' +console.log(anyString.substring(0, 7)); +console.log(anyString.substring(0, 10)); +</pre> + +<h3 id="Using_substring()_with_length_property">Using <code>substring()</code> with <code>length</code> property</h3> + +<p>The following example uses the <code>substring()</code> method and {{jsxref("String.length", "length")}} property to extract the last characters of a particular string. This method may be easier to remember, given that you don't need to know the starting and ending indices as you would in the above examples.</p> + +<pre class="brush: js">// Displays 'illa' the last 4 characters +var anyString = 'Mozilla'; +var anyString4 = anyString.substring(anyString.length - 4); +console.log(anyString4); + +// Displays 'zilla' the last 5 characters +var anyString = 'Mozilla'; +var anyString5 = anyString.substring(anyString.length - 5); +console.log(anyString5); +</pre> + +<h3 id="The_difference_between_substring()_and_substr()">The difference between <code>substring()</code> and <code>substr()</code></h3> + +<p>There's a subtle difference between the <code>substring()</code> and {{jsxref("String.substr", "substr()")}} methods, so you should be careful not to get them confused.</p> + +<p>The arguments of <code>substring()</code> represent the starting and ending indexes, while the arguments of <code>substr()</code> represent the starting index and the number of characters to include in the returned string.</p> + +<pre class="brush: js">var text = 'Mozilla'; +console.log(text.substring(2,5)); // => "zil" +console.log(text.substr(2,3)); // => "zil"</pre> + +<h3 id="Differences_between_substring()_and_slice()">Differences between <code>substring()</code> and <code>slice()</code></h3> + +<p>The <code>substring()</code> and {{jsxref("String.slice", "slice()")}} methods are almost identical, but there are a couple of subtle differences between the two, especially in the way negative arguments are dealt with.</p> + +<p>The <code>substring()</code> method swaps its two arguments if <code><var>indexStart</var></code> is greater than <code><var>indexEnd</var></code>, meaning that a string is still returned. The {{jsxref("String.slice", "slice()")}} method returns an empty string if this is the case.</p> + +<pre class="brush: js">var text = 'Mozilla'; +console.log(text.substring(5, 2)); // => "zil" +console.log(text.slice(5, 2)); // => "" +</pre> + +<p>If either or both of the arguments are negative or <code>NaN</code>, the <code>substring()</code> method treats them as if they were <code>0</code>.</p> + +<pre class="brush: js">console.log(text.substring(-5, 2)); // => "Mo" +console.log(text.substring(-5, -2)); // => "" +</pre> + +<p><code>slice()</code> also treats <code>NaN</code> arguments as <code>0</code>, but when it is given negative values it counts backwards from the end of the string to find the indexes.</p> + +<pre class="brush: js">console.log(text.slice(-5, 2)); // => "" +console.log(text.slice(-5, -2)); // => "zil" +</pre> + +<p>See the {{jsxref("String.slice", "slice()")}} page for more examples with negative numbers.</p> + +<h3 id="Replacing_a_substring_within_a_string">Replacing a substring within a string</h3> + +<p>The following example replaces a substring within a string. It will replace both individual characters and substrings. The function call at the end of the example changes the string <code>Brave New World</code> to <code>Brave New Web</code>.</p> + +<pre class="brush: js">// Replaces oldS with newS in the string fullS +function replaceString(oldS, newS, fullS) { + for (var i = 0; i < fullS.length; ++i) { + if (fullS.substring(i, i + oldS.length) == oldS) { + fullS = fullS.substring(0, i) + newS + fullS.substring(i + oldS.length, fullS.length); + } + } + return fullS; +} + +replaceString('World', 'Web', 'Brave New World'); +</pre> + +<p>Note that this can result in an infinite loop if <code>oldS</code> is itself a substring of <code>newS</code> — for example, if you attempted to replace 'World' with 'OtherWorld' here. A better method for replacing strings is as follows:</p> + +<pre class="brush: js">function replaceString(oldS, newS, fullS) { + return fullS.split(oldS).join(newS); +} +</pre> + +<p>The code above serves as an example for substring operations. If you need to replace substrings, most of the time you will want to use {{jsxref("String.prototype.replace()")}}.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.substring', 'String.prototype.substring')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.substring', 'String.prototype.substring')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.15', 'String.prototype.substring')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Implemented in JavaScript 1.0.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.substring")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("String.prototype.substr()")}} {{deprecated_inline}}</li> + <li>{{jsxref("String.prototype.slice()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/tolowercase/index.html b/files/ko/web/javascript/reference/global_objects/string/tolowercase/index.html new file mode 100644 index 0000000000..d91e48729f --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/tolowercase/index.html @@ -0,0 +1,83 @@ +--- +title: String.prototype.toLowerCase() +slug: Web/JavaScript/Reference/Global_Objects/String/toLowerCase +tags: + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/toLowerCase +--- +<div>{{JSRef}}</div> + +<div><strong><code>toLowerCase()</code></strong> 메서드는 문자열을 소문자로 변환해 반환합니다.</div> + +<div> </div> + +<div>{{EmbedInteractiveExample("pages/js/string-tolowercase.html")}}</div> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>str</var>.toLowerCase()</code></pre> + +<h3 id="반환값">반환값</h3> + +<p>호출 문자열을 소문자로 변환한 새로운 문자열</p> + +<h2 id="설명">설명</h2> + +<p><code>toLowerCase()</code> 메서드는 호출 문자열을 소문자로 변환해 반환합니다. <code>toLowerCase()</code> 는 원래의 <code>str</code>에 영향을 주지 않습니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="toLowerCase()"> <code>toLowerCase()</code></h3> + +<pre class="brush: js">console.log('ALPHABET'.toLowerCase()); // 'alphabet' +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">표준</th> + <th scope="col">상태</th> + <th scope="col">비고</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.16', 'String.prototype.toLowerCase')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.tolowercase', 'String.prototype.toLowerCase')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.tolowercase', 'String.prototype.toLowerCase')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.toLowerCase")}}</p> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("String.prototype.toLocaleLowerCase()")}}</li> + <li>{{jsxref("String.prototype.toLocaleUpperCase()")}}</li> + <li>{{jsxref("String.prototype.toUpperCase()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/tosource/index.html b/files/ko/web/javascript/reference/global_objects/string/tosource/index.html new file mode 100644 index 0000000000..d08a2a816a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/tosource/index.html @@ -0,0 +1,49 @@ +--- +title: String.prototype.toSource() +slug: Web/JavaScript/Reference/Global_Objects/String/toSource +translation_of: Web/JavaScript/Reference/Global_Objects/String/toSource +--- +<div>{{JSRef}} {{non-standard_header}}</div> + +<p>The <strong><code>toSource()</code></strong> method returns a string representing the source code of the object.</p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox"><code>String.toSource() +<var>str</var>.toSource() +</code></pre> + +<h3 id="리턴_값">리턴 값</h3> + +<p>호출한 객체의 소스코드가 <code>string</code>으로 보여집니다.</p> + +<h2 id="설명">설명</h2> + +<p><code>toSource()</code> 메소드는 다음 값을 리턴:</p> + +<p>For the built-in {{jsxref("String")}} object, <code>toSource()</code> returns the following string indicating that the source code is not available:</p> + +<pre class="brush: js">function String() { + [native code] +} +</pre> + +<p>For instances of {{jsxref("String")}} or string literals, <code>toSource()</code> returns a string representing the source code.</p> + +<p>This method is usually called internally by JavaScript and not explicitly in code.</p> + +<h2 id="Specifications">Specifications</h2> + +<p>Not part of any standard. Implemented in JavaScript 1.3.</p> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.toSource")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Object.prototype.toSource()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/tostring/index.html b/files/ko/web/javascript/reference/global_objects/string/tostring/index.html new file mode 100644 index 0000000000..999d5c0c74 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/tostring/index.html @@ -0,0 +1,59 @@ +--- +title: String.prototype.toString() +slug: Web/JavaScript/Reference/Global_Objects/String/toString +translation_of: Web/JavaScript/Reference/Global_Objects/String/toString +--- +<div><font><font>{{JSRef}}</font></font></div> + +<p><font><font>이 </font></font><strong><code>toString()</code></strong><font><font>메소드는 지정된 객체를 나타내는 문자열을 반환합니다.</font></font></p> + +<div><font><font>{{EmbedInteractiveExample ( "pages / js / string-tostring.html")}}</font></font></div> + +<h2 id="통사론"><font><font>통사론</font></font></h2> + +<pre class="syntaxbox"><code><var>str</var>.toString()</code></pre> + +<h3 id="반환_값"><font><font>반환 값</font></font></h3> + +<p><font><font>호출 객체를 나타내는 문자열</font></font></p> + +<h2 id="기술"><font><font>기술</font></font></h2> + +<p><font><font>{{jsxref ( "String")}} 오브젝트 </font></font><code>toString()</code><font><font>는 {{jsxref ( "Object")}} 오브젝트 </font><font>의 </font><font>메소드를 </font><font>대체 </font><font>합니다. </font><font>{{jsxref ( "Object.prototype.toString ()")}}을 상속하지 않습니다. </font><font>{{jsxref ( "String")}} 오브젝트의 경우 </font></font><code>toString()</code><font><font>메소드는 </font><font>오브젝트 </font><font>의 문자열 표시를 리턴하며 {{jsxref ( "String.prototype.valueOf ()")}} 메소드와 동일합니다.</font></font></p> + +<h2 id="예"><font><font>예</font></font></h2> + +<h3 id="사용_toString"><font><font>사용 </font></font><code>toString()</code></h3> + +<p><font><font>다음 예제는 {{jsxref ( "String")}} 오브젝트의 문자열 값을 표시합니다.</font></font></p> + +<pre class="brush: js"><font><font>var x = new String ( 'Hello world');</font></font> +<font><font> +console.log (x.toString ()); </font><font>// 'Hello world'를 기록합니다.</font></font> +</pre> + +<h2 id="명세서"><font><font>명세서</font></font></h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col"><font><font>사양</font></font></th> + </tr> + <tr> + <td><font><font>{{SpecName ( 'ESDraft', '# sec-string.prototype.tostring', 'String.prototype.toString')}}}</font></font></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성"><font><font>브라우저 호환성</font></font></h2> + +<p class="hidden"><font><font>이 페이지의 호환성 표는 구조화 된 데이터에서 생성됩니다. </font><font>데이터에 기여하려면 </font></font><a href="https://github.com/mdn/browser-compat-data"><font><font>https://github.com/mdn/browser-compat-data</font></font></a><font><font> 를 확인하고 </font><font>풀 요청을 보내주십시오.</font></font></p> + +<p><font><font>{{Compat ( "javascript.builtins.String.toString")}}</font></font></p> + +<h2 id="또한보십시오"><font><font>또한보십시오</font></font></h2> + +<ul> + <li><font><font>{{jsxref ( "Object.prototype.toSource ()")}}</font></font></li> + <li><font><font>{{jsxref ( "String.prototype.valueOf ()")}}</font></font></li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/touppercase/index.html b/files/ko/web/javascript/reference/global_objects/string/touppercase/index.html new file mode 100644 index 0000000000..f6a0c8f05c --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/touppercase/index.html @@ -0,0 +1,105 @@ +--- +title: String.prototype.toUpperCase() +slug: Web/JavaScript/Reference/Global_Objects/String/toUpperCase +tags: + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/toUpperCase +--- +<div>{{JSRef}}</div> + +<p><strong><code>toUpperCase()</code></strong> 메서드는 문자열을 대문자로 변환해 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/string-touppercase.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>str</var>.toUpperCase()</pre> + +<h3 id="반환_값">반환 값</h3> + +<p>대문자로 변환한 새로운 문자열.</p> + +<h3 id="예외">예외</h3> + +<dl> + <dt>{{jsxref("TypeError")}}</dt> + <dd>{{jsxref("Function.prototype.call()")}} 등을 사용해 {{jsxref("null")}}이나 {{jsxref("undefined")}}에서 호출 시.</dd> +</dl> + +<h2 id="설명">설명</h2> + +<p><code>toUpperCase()</code> 메서드는 문자열을 대문자로 변환한 값을 반환합니다. JavaScript의 문자열은 불변하므로 원본 문자열에는 영향을 주지 않습니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="기본_사용법">기본 사용법</h3> + +<pre class="brush: js">console.log('alphabet'.toUpperCase()); // 'ALPHABET'</pre> + +<h3 id="문자열이_아닌_this의_문자열_변환">문자열이 아닌 <code>this</code>의 문자열 변환</h3> + +<p><code>toUpperCase()</code>의 <code>this</code>가 문자열이 아니고, <code>undefined</code>와 <code>null</code>도 아니면 자동으로 문자열로 변환합니다.</p> + +<pre class="brush: js">const a = String.prototype.toUpperCase.call({ + toString: function toString() { + return 'abcdef'; + } +}); + +const b = String.prototype.toUpperCase.call(true); + +// prints out 'ABCDEF TRUE'. +console.log(a, b); +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + <th scope="col">상태</th> + <th scope="col">비고</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.18', 'String.prototype.toUpperCase')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.touppercase', 'String.prototype.toUpperCase')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.touppercase', 'String.prototype.toUpperCase')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.String.toUpperCase")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("String.prototype.toLocaleLowerCase()")}}</li> + <li>{{jsxref("String.prototype.toLocaleUpperCase()")}}</li> + <li>{{jsxref("String.prototype.toLowerCase()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/trim/index.html b/files/ko/web/javascript/reference/global_objects/string/trim/index.html new file mode 100644 index 0000000000..0f0b71f548 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/trim/index.html @@ -0,0 +1,97 @@ +--- +title: String.prototype.trim() +slug: Web/JavaScript/Reference/Global_Objects/String/Trim +tags: + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/Trim +--- +<div>{{JSRef}}</div> + +<p><strong><code>trim()</code></strong> 메서드는 문자열 양 끝의 공백을 제거합니다. 공백이란 모든 공백문자(space, tab, NBSP 등)와 모든 개행문자(LF, CR 등)를 의미합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/string-trim.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><var>str</var>.trim()</pre> + +<h3 id="반환_값">반환 값</h3> + +<p>양 끝에서 공백을 제거한 새로운 문자열.</p> + +<h2 id="설명">설명</h2> + +<p><code>trim()</code> 메서드는 양끝의 공백을 제거한 문자열을 반환합니다. <code>trim()</code>은 원본 문자열에는 영향을 주지 않습니다. </p> + +<h2 id="예제">예제</h2> + +<h3 id="trim()_사용"><code>trim()</code> 사용</h3> + +<p>아래의 예제는 소문자 문자열 <code>'foo'</code>를 표시합니다.</p> + +<pre class="brush: js">var orig = ' foo '; +console.log(orig.trim()); // 'foo' + +// 한 쪽의 공백만 제거하는 .trim() 예제 + +var orig = 'foo '; +console.log(orig.trim()); // 'foo' +</pre> + +<h2 id="폴리필">폴리필</h2> + +<p>다른 코드 전에 아래 코드를 실행하면 지원하지 않는 환경에서도 <code>String.trim()</code> 을 사용할 수 있습니다.</p> + +<pre class="brush: js">if (!String.prototype.trim) { + String.prototype.trim = function () { + return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); + }; +} +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">표준</th> + <th scope="col">상태</th> + <th scope="col">비고</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.20', 'String.prototype.trim')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.8.1.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.trim', 'String.prototype.trim')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.trim', 'String.prototype.trim')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.trim")}}</p> + +<h2 id="참조">참조</h2> + +<ul> + <li>{{jsxref("String.prototype.trimLeft()")}} {{non-standard_inline}}</li> + <li>{{jsxref("String.prototype.trimRight()")}} {{non-standard_inline}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/string/valueof/index.html b/files/ko/web/javascript/reference/global_objects/string/valueof/index.html new file mode 100644 index 0000000000..e8e217d615 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/valueof/index.html @@ -0,0 +1,83 @@ +--- +title: String.prototype.valueOf() +slug: Web/JavaScript/Reference/Global_Objects/String/valueOf +tags: + - 메서드 + - 문자열 + - 자바스크립트 + - 참고 + - 프로토타입 +translation_of: Web/JavaScript/Reference/Global_Objects/String/valueOf +--- +<div>{{JSRef}}</div> + +<p><strong><code>valueOf()</code></strong> 메서드는 {{jsxref("String")}} 객체의 원시값을 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/string-valueof.html")}}</div> + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox"><code><var>str</var>.valueOf()</code></pre> + +<h3 id="반환_값">반환 값</h3> + +<p>지정된 {{jsxref("String")}} 객체의 원시 값을 나타내는 문자열.</p> + +<h2 id="설명">설명</h2> + +<p>{{jsxref("String")}} 의 <code>valueOf()</code> 메서드는 {{jsxref("String")}} 객체의 원시 값을 문자열 데이터 타입으로 반환 합니다. 이 값은 {{jsxref("String.prototype.toString()")}}.과 동일합니다.</p> + +<p>이 메서드는 보통 자바스크립트에 의해 내부적으로 호출되며, 코드에서 명시적으로 사용하지는 않습니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="valueOf_사용"> <code>valueOf()</code> 사용</h3> + +<pre class="brush: js">var x = new String('Hello world'); +console.log(x.valueOf()); // 'Hello world' 가 보여집니다. +</pre> + +<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('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>초기 정의. JavaScript 1.1 에서 구현.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.3', 'String.prototype.valueOf')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.valueof', 'String.prototype.valueOf')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.valueof', 'String.prototype.valueOf')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p class="hidden">이 페이지의 호환성 표는 구조화된 데이터로부터 생성됩니다. 만약 데이터에 기여하고 싶다면, <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> 을 확인하시고 pull 요청을 보내주세요.</p> + +<p>{{Compat("javascript.builtins.String.valueOf")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{jsxref("String.prototype.toString()")}}</li> + <li>{{jsxref("Object.prototype.valueOf()")}}</li> +</ul> |