From da78a9e329e272dedb2400b79a3bdeebff387d47 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:17 -0500 Subject: initial commit --- .../global_objects/string/charat/index.html | 260 ++++++++++++++++++ .../global_objects/string/charcodeat/index.html | 169 ++++++++++++ .../global_objects/string/concat/index.html | 105 ++++++++ .../global_objects/string/endswith/index.html | 142 ++++++++++ .../global_objects/string/fromcharcode/index.html | 101 +++++++ .../global_objects/string/includes/index.html | 125 +++++++++ .../reference/global_objects/string/index.html | 298 ++++++++++++++++++++ .../global_objects/string/indexof/index.html | 159 +++++++++++ .../global_objects/string/lastindexof/index.html | 105 ++++++++ .../global_objects/string/length/index.html | 84 ++++++ .../global_objects/string/localecompare/index.html | 159 +++++++++++ .../global_objects/string/match/index.html | 156 +++++++++++ .../global_objects/string/normalize/index.html | 163 +++++++++++ .../global_objects/string/padend/index.html | 99 +++++++ .../global_objects/string/padstart/index.html | 104 +++++++ .../global_objects/string/prototype/index.html | 218 +++++++++++++++ .../global_objects/string/repeat/index.html | 113 ++++++++ .../global_objects/string/replace/index.html | 299 +++++++++++++++++++++ .../global_objects/string/search/index.html | 100 +++++++ .../global_objects/string/slice/index.html | 129 +++++++++ .../global_objects/string/split/index.html | 231 ++++++++++++++++ .../global_objects/string/startswith/index.html | 95 +++++++ .../global_objects/string/substr/index.html | 131 +++++++++ .../global_objects/string/substring/index.html | 190 +++++++++++++ .../global_objects/string/tolowercase/index.html | 83 ++++++ .../global_objects/string/tosource/index.html | 49 ++++ .../global_objects/string/tostring/index.html | 59 ++++ .../global_objects/string/touppercase/index.html | 105 ++++++++ .../global_objects/string/trim/index.html | 97 +++++++ .../global_objects/string/valueof/index.html | 83 ++++++ 30 files changed, 4211 insertions(+) create mode 100644 files/ko/web/javascript/reference/global_objects/string/charat/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/charcodeat/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/concat/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/endswith/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/fromcharcode/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/includes/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/indexof/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/lastindexof/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/length/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/localecompare/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/match/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/normalize/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/padend/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/padstart/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/prototype/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/repeat/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/replace/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/search/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/slice/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/split/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/startswith/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/substr/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/substring/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/tolowercase/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/tosource/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/tostring/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/touppercase/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/trim/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/valueof/index.html (limited to 'files/ko/web/javascript/reference/global_objects/string') 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 +--- +
{{JSRef}}
+ +

charAt() 함수는 문자열에서 특정 인덱스에 위치하는  유니코드 단일문자를 반환합니다. 

+ +
{{EmbedInteractiveExample("pages/js/string-charat.html")}}
+ + + +

구문

+ +
str.charAt(index)
+ +

매개변수

+ + + +
+
index
+
+ +

반환 값

+ + + +

설명

+ +

문자열 내의 문자는 왼쪽에서 오른쪽으로 순번(인덱스)이 매겨집니다. 첫 번째 문자의 순번은 0, 그리고 stringName 이라는 이름을 가진 문자열의 마지막 문자 순번은 stringName.length - 1 입니다. index가 문자열 길이를 벗어나면 빈 문자열을 반환하게 됩니다.

+ +

index를 제공하지 않으면 기본값은 0입니다.

+ +

예제

+ +

문자열 내의 다른 위치에 있는 문자들을 출력하기

+ +

아래 예제는 문자열 "Brave new world"의 다른 위치에 있는 문자들을 출력합니다.

+ +
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) + "'");
+
+ +

프로그램의 실행 결과는 아래와 같습니다.

+ +
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 ''
+
+ +

문자열 내의 모든 문자 얻기

+ +

아래 예제는 문자열 전체를 순회하며 각 문자가 완전한지 확인하는 프로그램입니다. 심지어 기본 다국어 평면(Basic Multilingual Plane)에 포함되지 않은 문자들이 포함되어 있다고 하더라도 잘 동작합니다. 

+ +
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;
+}
+
+ +

비구조화 할당을 허용하는 ECMAScript 2016 환경에서는 아래 예제 코드가 더 간결하고, 문자가 서러게이트 페어가 되는 것을 허용할 때는 증가해야 하는 변수를 자동적으로 증가하기에 위의 코드보다 다소 더 유연합니다.

+ +
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];
+}
+
+ +

기본다국어평면(Basic-Multilingual-Plane)이 아닌 문자들을 지원하도록 charAt() 수정하기

+ +

어떠한 non-BMP 문자들이 나타났는지 호출자가 알 필요가 없기 때문에 non-BMP 문자들을 지원하도록 하는데는 앞의 예제들이 더 자주 사용되지만, 인덱스로 문자를 선택하는데 있어서 문자열 내에 서로게이트 페어들이 하나의 문자들로 처리되길 원한다면, 아래 예제 코드를 사용하면 됩니다.

+ +
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;
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.5.4.4', 'String.prototype.charAt')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.charat', 'String.prototype.charAt')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.charat', 'String.prototype.charAt')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.String.charAt")}}

+ +

관련문서

+ + 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 +--- +
{{JSRef}}
+ +

charCodeAt() 메서드는 주어진 인덱스에 대한 UTF-16 코드를 나타내는 0부터 65535 사이의 정수를 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/string-charcodeat.html")}}
+ + + +

전체 코드 값을 원하신다면 {{jsxref("String.prototype.codePointAt()")}}을 사용하세요.

+ +

구문

+ +
str.charCodeAt(index)
+ +

매개변수

+ +
+
index
+
0 이상이고 문자열의 길이보다 작은 정수. 숫자가 아니라면 0을 기본값으로 사용함. 
+
+ +

반환 값

+ +

주어진 인덱스 대한 문자에 대한 UTF-16 코드를 나타내는 숫자
+ 범위 밖으로 넘어갔을 경우 {{jsxref("Global_Objects/NaN", "NaN")}}

+ +

설명

+ +

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 JavaScript Guide.

+ +

Note that charCodeAt() 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 charCodeAt(i), but also charCodeAt(i+1) (as if examining/reproducing a string with two letters), or to use codePointAt(i) instead. See example 2 and 3 below.

+ +

charCodeAt() 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.

+ +

Backward compatibilty: In historic versions (like JavaScript 1.2) the charCodeAt() 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.

+ +

예제

+ +

Using charCodeAt()

+ +

The following example returns 65, the Unicode value for A.

+ +
'ABC'.charCodeAt(0); // returns 65
+
+ +

Fixing charCodeAt() to handle non-Basic-Multilingual-Plane characters if their presence earlier in the string is unknown

+ +

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.

+ +
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;
+}
+
+ +

Fixing charCodeAt() to handle non-Basic-Multilingual-Plane characters if their presence earlier in the string is known

+ +
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;
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.5.4.5', 'String.prototype.charCodeAt')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.charcodeat', 'String.prototype.charCodeAt')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.charcodeat', 'String.prototype.charCodeAt')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.String.charCodeAt")}}

+ +

같이 보기

+ + 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 +--- +
{{JSRef}}
+ +

concat() 메서드는 매개변수로 전달된 모든 문자열을 호출 문자열에 붙인 새로운 문자열을 반환합니다.

+ +

{{EmbedInteractiveExample("pages/js/string-concat.html")}}

+ +

구문

+ +
str.concat(string2, string3[, ..., stringN])
+ +

매개변수

+ +
+
string2...stringN
+
합칠 문자열.
+
+ +

반환값

+ +

주어진 문자열을 모두 붙인 새로운 문자열.

+ +

설명

+ +

concat() 함수는 호출 문자열에 문자열 인수를 이어 붙인 결과를 반환합니다. 원본 문자열과 결과 문자열의 변형은 서로에게 영향을 미치지 않습니다. 인수가 문자열이 아니면 계산 전에 문자열로 변환합니다.

+ +

예제

+ +

concat() 사용하기

+ +

아래 예제에서는 문자열을 결합하여 새로운 문자열을 만듭니다.

+ +
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"
+ +

성능

+ +

concat() 메서드보다 {{jsxref("Operators/Assignment_Operators", "할당 연산자", "", 1)}} (+, +=)를 사용하는게 더 좋습니다. 성능 테스트 결과에 따르면 할당 연산자의 속도가 몇 배 빠릅니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.5.4.6', 'String.prototype.concat')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-string.prototype.concat', 'String.prototype.concat')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-string.prototype.concat', 'String.prototype.concat')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.String.concat")}}

+ +
+ +
+ +

관련문서

+ + 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 +--- +
{{JSRef}}
+ +

The endsWith() 메서드를 사용하여 어떤 문자열에서 특정 문자열로 끝나는지를 확인할 수 있으며, 그 결과를 true 혹은 false로 반환한다. 

+ +

문법

+ +
str.endsWith(searchString[, length])
+ +

파라미터들

+ +
+
searchString
+
이 문자열의 끝이 특정 문자열로 끝나는지를 찾기 원하는 문자열입니다.
+
length
+
옵션입니다. 찾고자 하는 문자열의 길이값이며, 기본값은 문자열 전체 길이입니다. 문자열의 길이값은 문자열 전체 길이 안에서만 존재하여야 합니다.
+
+ +

반환 값

+ +

문자열의 끝이 주어진 문자열로 끝나면 true, 그렇지 않다면 false

+ +

설명

+ +

여러분은 이 메서드를 사용하여 어떤 문자열이 특정 문자열로 끝나는지를 확인할 수 있습니다.

+ +

예제

+ +

endsWith() 사용하기

+ +
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
+
+ +

Polyfill

+ +

이 메서드는 ECMAScript 6 규격에 포함되었습니다만 아직까지는 모든 JavaScrpt가 이 기능을 지원하고 있지는 않습니다. 하지만 여러분은 String.prototype.endsWith() 메서드를 다음과 같이 쉽게 polyfill 할 수 있습니다:

+ +
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;
+  };
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-string.prototype.endswith', 'String.prototype.endsWith')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-string.prototype.endswith', 'String.prototype.endsWith')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)EdgeInternet ExplorerOperaSafari
Basic support{{CompatChrome("41")}}{{CompatGeckoDesktop("17")}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatSafari("9")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatChrome("36")}}{{CompatGeckoMobile("17")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

관련문서

+ + 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 +--- +
{{JSRef}}
+ +

String.fromCharCode() 메서드는 UTF-16 코드 유닛의 시퀀스로부터 문자열을 생성해 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/string-fromcharcode.html")}}
+ + + +

구문

+ +
String.fromCharCode(num1[, ...[, numN]])
+ +

매개변수

+ +
+
num1, ..., numN
+
UTF-16 코드 유닛인 숫자 뭉치. 가능한 값의 범위는 0부터 65535(0xFFFF)까지입니다. 0xFFFF를 초과하는 값은 잘립니다. 유효성 검사는 하지 않습니다.
+
+ +

반환 값

+ +

주어진 UTF-16 코드 유닛 N개로 이루어진 문자열.

+ +

설명

+ +

이 메서드는 {{jsxref("String")}} 객체가 아닌 문자열을 반환합니다.

+ +

fromCharCode()는 {{jsxref("String")}}의 정적 메서드이기 때문에 String.fromCharCode()로 사용해야 합니다.

+ +

예제

+ +

fromCharCode() 사용하기

+ +

다음 예제는 문자열 "ABC"를 반환합니다..

+ +
String.fromCharCode(65, 66, 67);  // "ABC"
+String.fromCharCode(0x2014)       // "—"
+String.fromCharCode(0x12014)      // 숫자 '1'은 무시해서 "—"
+
+ +

더 큰 값과 사용하기

+ +

초기 JavaScript 표준화 과정에서 예상했던 것처럼, 대부분의 흔한 유니코드 값을 16비트 숫자로 표현할 수 있고, fromCharCode()가 많은 흔한 값에서 하나의 문자를 반환할 수 있지만, 모든 유효한 유니코드 값(최대 21비트)을 처리하려면 fromCharCode()만으로는 부족합니다. 높은 코드 포인트의 문자는 써로게이트surrogate 값 두 개를 합쳐 하나의 문자를 표현하므로,{{jsxref("String.fromCodePoint()")}}(ES2015 표준) 메서드는 그러한 쌍을 높은 값의 문자로 변환할 수 있습니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.5.3.2', 'StringfromCharCode')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.fromcharcodes', 'String.fromCharCode')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.fromcharcodes', 'String.fromCharCode')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.String.fromCharCode")}}

+ +

같이 보기

+ + 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 +--- +
{{JSRef}}
+ +

includes() 메서드는 하나의 문자열이 다른 문자열에 포함되어 있는지를 판별하고, 결과를 true 또는 false 로 반환합니다.

+ +

{{EmbedInteractiveExample("pages/js/string-includes.html")}}

+ +

구문

+ +
str.includes(searchString[, position])
+ +

매개변수

+ +
+
searchString
+
이 문자열에서 찾을 다른 문자열.
+
position {{optional_inline}}
+
searchString을 찾기 시작할 위치. 기본값 0.
+
+ +

반환값

+ +

문자열을 찾아내면 true. 실패하면 false.

+ +

설명

+ +

includes() 메서드를 사용해 문자열 내에 찾고자 하는 다른 문자열이 있는지 확인할 수 있습니다.

+ +

대소문자 구분

+ +

includes() 메서드는 대소문자를 구별합니다. 예를 들어 아래 코드는 false를 반환합니다.

+ +
'Blue Whale'.includes('blue'); // returns false
+
+ +

예제

+ +

includes() 사용하기

+ +
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
+
+ +

폴리필

+ +

이 메서드는 ECMAScript 6 규격에 포함되었습니다만 아직까지는 모든 JavaScrpt가 이 기능을 지원하고 있지는 않습니다. 하지만 여러분은 이 메서드를 다음과 같이 쉽게 polyfill 할 수 있습니다.

+ +
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;
+    }
+  };
+}
+
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-string.prototype.includes', 'String.prototype.includes')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-string.prototype.includes', 'String.prototype.includes')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.String.includes")}}
+ +

String.prototype.contains

+ +

Firefox 18 - 39에서, include() 메서드의 이름은 contains()이었습니다. contains() 함수는 아래와 같은 이유로 {{bug(1102219)}}에서 includes()로 변경되었습니다:

+ +

It's been reported that some websites using MooTools 1.2 broke on Firefox 17. This version of MooTools checks whether String.prototype.contains() 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' String.prototype.contains() implementation to break. As a result, the implementation was disabled in Firefox 17 and String.prototype.contains() was available one version later, in Firefox 18, when outreach to MooTools was leading to the release of MooTools version 1.2.6.

+ +

MooTools 1.3 forces its own version of String.prototype.contains(), so websites relying on it should not break. However, you should note that MooTools 1.3 signature and ECMAScript 6 signatures for this method differ (on the second argument). Later, MooTools 1.5+ changed the signature to match the ES6 standard.

+ +

Firefox 48에서, String.prototype.contains()은 제거되었습니다. 오직 String.prototype.includes()만 사용할 수 있습니다.

+ +

관련문서

+ + 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 +--- +
{{JSRef}}
+ +

String 전역 객체는 문자열(문자의 나열)의 생성자입니다.

+ +

구문

+ +

문자열 리터럴은 다음과 같은 형식을 사용합니다.

+ +
'string text'
+"string text"
+"中文 español Deutsch English देवनागरी العربية português বাংলা русский 日本語 norsk bokmål ਪੰਜਾਬੀ 한국어 தமிழ் עברית"
+ +

문자열은 String 전역 객체를 직접 사용하여 생성할 수 있습니다.

+ +
String(thing)
+ +

매개변수

+ +
+
thing
+
문자열로 변환할 아무 값.
+
+

템플릿 리터럴

+
+
+ +

ECMAScript 2015 이후, 문자열 리터럴은 소위 템플릿 리터럴이 될 수 있습니다.

+ +
`hello world` `hello! world!` `hello ${who}` tag `<a>${who}</a>`
+ +

이스케이프 표현

+ +

일반적인 출력 문자 외의 특수 문자는 이스케이프 표현을 사용해 적을 수 있습니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
코드출력
\XXX8진수 Latin-1 문자
\'작은따옴표
\"큰따옴표
\\역슬래시
\n개행
\r캐리지 리턴
\v세로 탭
\t
\b백 스페이스
\f폼 피드
\uXXXX유니코드 코드포인트
\u{X} ... \u{XXXXXX}유니코드 코드포인트 {{experimental_inline}}
\xXXLatin-1 문자
+ +
+

일부 다른 프로그래밍 언어와 달리, JavaScript는 작은따옴표와 큰따옴표 문자열을 구분하지 않습니다. 따라서 위의 이스케이프 문자는 작은따옴표나 큰따옴표에서 상관 없이 작동합니다.

+
+ +

긴 문자열 리터럴

+ +

작성한 코드가 매우 긴 문자열을 포함해야 하는 경우, 끝 없이 뻗어나가는 한 줄이나 편집기의 재량에 따라 자동으로 줄을 넘기는 대신 직접 여러 줄로 나누되 내용에는 영향을 주지 않고 싶을 때가 있을겁니다. 이런 상황에는 두 가지 방법을 사용할 수 있습니다.

+ +

우선 다음과 같이 + 연산자를 사용할 수 있습니다.

+ +
let longString = "여러 줄에 걸쳐 작성해야 할 정도로 " +
+                 "긴 문자열인데 왜 한 줄에 다 적으면 안되냐면 " +
+                 "코드를 읽기 힘들어지니까요.";
+ +

아니면 역슬래시 문자("\")를 각 줄의 맨 끝에 붙여 문자열이 이어진다는걸 표시할 수도 있습니다. 역슬래시 다음에 공백을 포함한 어떤 문자라도 붙으면 제대로 작동하지 않으므로 주의해야 합니다.

+ +
let longString = "여러 줄에 걸쳐 작성해야 할 정도로 \
+긴 문자열인데 왜 한 줄에 다 적으면 안되냐면 \
+코드를 읽기 힘들어지니까요.";
+ +

두 예시 모두 동일한 문자열을 생성합니다.

+ +

설명

+ +

문자열은 텍스트 형태로 표현될 수있는 데이터를 보관하는 데 유용합니다. 문자열에서 가장 많이 사용되는 작업들은 문자열의 길이를 확인하는 ({{jsxref("String.length", "length")}}), 문자열을 생성하고 연결하는 + 와 += 문자열 연산자, 서브문자열(substring)이 있는지 확인하고, 있으면 위치를 확인하는 {{jsxref("String.prototype.indexOf()", "indexOf()")}} 메서드, 서브문자열(substring)을 추출해내는 {{jsxref("String.prototype.substring()", "substring()")}} 메서드가 있습니다.

+ +

문자 접근

+ +

문자열에서 개개의 문자에 접근할 수 있는 방법은 두가지가 있습니다. 첫번째는 {{jsxref("String.prototype.charAt()", "charAt()")}} 메서드를 이용하는 것입니다:

+ +
return 'cat'.charAt(1); // returns "a"
+
+ +

다른 방법(ECMAScript 5에서 소개하고 있는)은 문자열을 배열과 같은 오브젝트로 취급하여, 문자에 해당하는 숫자 인덱스를 사용하는 방법입니다 :

+ +
return 'cat'[1]; // returns "a"
+
+ +

브라켓([ ]) 표기법을 사용하여 문자에 접근하는 경우 , 이러한 프로퍼티들에 새로운 값을 할당하거나 삭제할 수는 없습니다. 포함되어 있는 프로퍼티들은 작성할 수도, 수정할 수도 없습니다. (더 자세한 정보는 {{jsxref("Object.defineProperty()")}}를 참고 바랍니다 .)

+ +

문자열 비교

+ +

C 개발자는 문자열 비교를 위하여 strcmp() 함수를 사용합니다. JavaScript에서는 단지 less-than와 greater-than 연산자만을 사용하여 문자열을 비교할 수 있습니다 :

+ +
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.");
+}
+
+ +

비슷한 결과를 얻을 수 있는 방법으로 String 인스턴스에서 상속된 {{jsxref("String.prototype.localeCompare()", "localeCompare()")}} 메서드를 사용할 수 있습니다.

+ +

문자열 원형과 String 객체의 차이

+ +
JavaScript는 String 오브젝트와 원형의 문자열을 다르게 취급한다는 것에 주의해야 합니다. ({{jsxref("Boolean")}}과 숫자의 true도 마찬가지입니다.)
+ +
 
+ +

문자열 리터럴(작은 따옴표 또는 큰 따옴표로 생성되는)과 생성자 없이(즉. {{jsxref("Operators/new", "new")}} 키워드를 사용하지 않고) String을 호출하여 반환된 문자열은 원형 문자열(primitive strings)입니다. JavaScript는 자동적으로 원형을 String 오브젝트로 변환하기 때문에, String 오브젝트 메서드를 사용하여 원형문자열을 생성할 수 있습니다. 문맥 안의 메서드에서 프로퍼티 조회 또는 원형의 문자열 호출이 발생하면, JavaScript는 자동으로 문자열 원형을 감싸고 프로퍼티 조회를 수행 하거나 메서드를 호출합니다.

+ +
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"
+
+ +

문자열 원형과 String 오브젝트는 {{jsxref("Global_Objects/eval", "eval()")}}을 사용할 때 다른 결과를 제공합니다. eval에 전달되는 문자열 원형들은 소스 코드 취급을 받습니다; String 오브젝트들은 다른 모든 오브젝트들과 마찬가지로 취급하며, 오브젝트를 반환합니다. 예를 들면:

+ +
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"
+
+ +

이러한 이유로, 비록 코드 상에서 원형 문자열을 사용하는 대신에 String 오브젝트를 사용하게 되면 코드가 손상될 수 있지만, 일반적인 개발자는 차이를 걱정할 필요는 없습니다.

+ +

String 오프젝트는 언제든지 {{jsxref("String.prototype.valueOf()", "valueOf()")}} 메서드로 원형에 대응하도록 전환할 수 있습니다.

+ +
console.log(eval(s2.valueOf())); // returns the number 4
+
+ +

속성

+ +
+
{{jsxref("String.prototype")}}
+
String 오브젝트는 프로퍼티의 추가가 가능합니다.
+
+ +

메서드

+ +
+
{{jsxref("String.fromCharCode()")}}
+
지정된 유니코 값의 순서를 이용하여 만든 문자열을 반환합니다.
+
{{jsxref("String.fromCodePoint()")}} {{experimental_inline}}
+
지정된 코드 포인트 순서를 이용하여 만든 문자열을 반환합니다.
+
{{jsxref("String.raw()")}} {{experimental_inline}}
+
원형 템플릿 문자열(raw template string)에서 생성된 문자열을 반환합니다.
+
+ +

String generic 메서드

+ +
+

String generic들은 비표준으로, 가까운 미래에 사라질 것입니다. 아래에서 제공하고 있는 방식을 사용하지 않으면, 브라우저들간의 호환성은 기대하기 어렵습니다. 

+
+ +

String 인스턴스 메서드는 JavScript 1.6으로 Firefox에서(ECMAScript 표준에 속하지는 않지만) 어떤 오브젝트라도 String 메서드에 적용하여 String 오브젝트에서 사용가능합니다:

+ +
var num = 15;
+console.log(String.replace(num, /5/, '2'));
+
+ +

{{jsxref("Global_Objects/Array", "Generics", "#Array_generic_methods", 1)}}은 {{jsxref("Global_Objects/Array", "Array")}} 메서드에도 사용 가능합니다.

+ +

String 인스턴스

+ +

속성

+ +

{{ page('ko/docs/JavaScript/Reference/Global_Objects/String/prototype', 'Properties') }}

+ +

메서드

+ +

HTML과 관계없는 메서드

+ +

{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Methods_unrelated_to_HTML')}}

+ +

HTML wrapper methods

+ +

{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'HTML_wrapper_methods')}}

+ +

예제

+ +

문자열 변환

+ +

비록 일반적으로 toString() 함수를 많이 사용하고 있지만, {{jsxref("String.prototype.toString()", "toString()")}}의 "안전한" 대안으로 String을 사용할 수 있습니다. String은 {{jsxref("Global_Objects/null", "null")}}과 {{jsxref("Global_Objects/undefined", "undefined")}}에 대해서도 잘 동작합니다. 예를 들면: 

+ +
var outputStrings = [];
+for (var i = 0, n = inputValues.length; i < n; ++i) {
+  outputStrings.push(String(inputValues[i]));
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.5', 'String')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string-objects', 'String')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string-objects', 'String')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.String",2)}}

+ +

같이 보기

+ + 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 +--- +
{{JSRef}}
+ +

indexOf() 메서드는 호출한 {{jsxref("String")}} 객체에서 주어진 값과 일치하는 첫 번째 인덱스를 반환합니다. 일치하는 값이 없으면 -1을 반환합니다. 

+ +
{{EmbedInteractiveExample("pages/js/string-indexof.html")}}
+ + + +
+

참고: {{jsxref("Array")}}에서는 {{jsxref("Array.prototype.indexOf()")}} 메서드가 같은 역할을 합니다.

+
+ +

구문

+ +
str.indexOf(searchValue[, fromIndex])
+ +

매개변수

+ +
+
searchValue
+
찾으려는 문자열. 아무 값도 주어지지 않으면 문자열 "undefined"를 찾으려는 문자열로 사용합니다.
+
fromIndex {{optional_inline}}
+
문자열에서 찾기 시작하는 위치를 나타내는 인덱스 값입니다. 어떤 정수값이라도 가능합니다. 기본값은 0이며, 문자열 전체를 대상으로 찾게 됩니다. 만약 fromIndex 값이 음의 정수이면 전체 문자열을 찾게 됩니다. 만약 fromIndex >= str.length 이면, 검색하지 않고 바로 -1을 반환합니다. searchValue가 공백 문자열이 아니라면, str.length를 반환합니다.
+
+ +

반환 값

+ +

searchValue의 첫 번째 등장 인덱스. 찾을 수 없으면 -1.

+ +

설명

+ +

문자열 내에 있는 문자들은 왼쪽에서 오른쪽 방향으로 순번이 매겨집니다. 제일 처음 문자는 0번째 순번(index)이며, stringName 문자열의 마지막 문자의 순번 stringName.length -1 입니다. 

+ +
'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
+ +

indexOf() 메서드는 대소문자를 구분합니다. 예를 들면, 아래 예제는 일치하는 문자열이 없으므로 -1을 반환합니다.

+ +
'Blue Whale'.indexOf('blue'); // returns -1
+
+ +

존재 여부 확인

+ +

'0'을 평가했을 때 true가 아니고, -1을 평가했을 때 false가 아닌 것에 주의해야 합니다. 따라서, 임의의 문자열에 특정 문자열이 있는지를 확인하는 올바른 방법은 다음과 같습니다.

+ +
'Blue Whale'.indexOf('Blue') !== -1; // true
+'Blue Whale'.indexOf('Bloe') !== -1; // false
+
+ +

예제

+ +

indexOf() 사용하기

+ +

아래 예제는 "Brave new world" 문자열의 위치를 확인하기 위해 indexOf()와 {{jsxref("String.prototype.lastIndexOf()", "lastIndexOf()")}} 를 사용하고 있습니다.

+ +
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
+
+ +

indexOf()와 대소문자 구분

+ +

아래 예제에서는 2개의 문자열 변수를 정의하고 있습니다. 이 변수들 내에 있는 문자열들은 모두 같지만 두 번째 변수에 포함되어 있는 문자열은 대문자를 포함하고 있습니다. 첫 번째 {{domxref("console.log()")}} 메서드의 결과값은 19입니다. 하지만, 두 번째 console.log() 메서드의 결과값은 -1입니다. 왜냐하면, indexOf() 메서드는 대소문자를 구분하기 때문에 myCapString에서 "cheddar" 문자열을 찾을 수 없기 때문입니다. 

+ +
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을 출력합니다.
+
+ +

indexOf()를 사용하여 문자열 내의 특정 문자 숫자 세기

+ +

아래 예제는 str 문자열에서 e 문자의 총 숫자를 확인하는 프로그램입니다:

+ +
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를 출력합니다.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.5.4.7', 'String.prototype.indexOf')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.indexof', 'String.prototype.indexOf')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.indexof', 'String.prototype.indexOf')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.String.indexOf")}}
+ +

같이 보기

+ + 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 +--- +
{{JSRef}}
+ +

lastIndexOf() 메서드는 주어진 값과 일치하는 부분을 fromIndex로부터 역순으로 탐색하여, 최초로 마주치는 인덱스를 반환합니다. 일치하는 부분을 찾을 수 없으면 -1을 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/string-lastindexof.html", "shorter")}}
+ + + +

구문

+ +
str.lastIndexOf(searchValue[, fromIndex])
+ +

매개변수

+ +
+
searchValue
+
탐색할 문자열. 빈 값을 제공할 경우 fromIndex를 반환합니다.
+
fromIndex {{optional_inline}}
+
탐색의 시작점으로 사용할 인덱스. 기본값은 +Infinity입니다. fromIndex >= str.length인 경우 모든 문자열을 탐색합니다. fromIndex < 0인 경우엔 0을 지정한 것과 동일합니다.
+
+ +

반환 값

+ +

문자열 내에서 searchValue가 마지막으로 등장하는 인덱스. 등장하지 않으면 -1.

+ +

설명

+ +

문자열의 문자는 왼쪽에서 오른쪽으로 인덱스를 매깁니다. 첫 번째 문자의 인덱스는 0이며, 마지막 문자의 인덱스는 str.length -1입니다.

+ +
'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 반환
+
+ +
+

참고: 'abab'.lastIndexOf('ab', 2)는 0이 아니고 2를 반환합니다. fromIndex는 탐색의 시작점만 제한하기 때문입니다.

+
+ +

대소문자 구분

+ +

lastIndexOf() 메서드는 대소문자를 구분합니다. 예를 들어, 아래 예제는 -1을 반환합니다.

+ +
'Blue Whale, Killer Whale'.lastIndexOf('blue'); // -1 반환
+
+ +

예제

+ +

indexOf()와 lastIndexOf() 사용하기

+ +

아래 예제는 문자열 "Brave new world" 내에서 특정 값의 위치를 확인하기 위해 {{jsxref("String.prototype.indexOf()", "indexOf()")}}와 lastIndexOf()를 사용합니다.

+ +
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
+
+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-string.prototype.lastindexof', 'String.prototype.lastIndexOf')}}
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.String.lastIndexOf")}}
+ +

같이 보기

+ + 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 +--- +
{{JSRef}}
+ +

length 속성은 UTF-16 코드 유닛을 기준으로 문자열의 길이를 나타냅니다.

+ +
{{EmbedInteractiveExample("pages/js/string-length.html")}}
+ + + +

설명

+ +

length 속성은 문자열 안의 코드 유닛 수를 반환합니다. JavaScript가 사용하는 문자열 형식인 {{interwiki("wikipedia", "UTF-16")}}은 대부분의 일반적인 문자를 표현하기 위해 하나의 16비트 코드 유닛을 사용합니다. 반면, 덜 쓰이는 문자를 표현하기 위해 2개의 코드 유닛을 사용해야 할 때도 있으므로 문자열 내에 있는 문자들의 실제 총 숫자가 length 속성이 반환하는 숫자와 일치하지 않을 수 있습니다.

+ +

ECMAScript 2016 7판은 최대 길이를 2^53 - 1로 설정했습니다. 이전엔 명시된 최대 길이가 없었습니다.

+ +

빈 문자열은 length가 0입니다.

+ +

정적 속성 String.length는 1을 반환합니다. 

+ +

예제

+ +

일반적인 사용법

+ +
var x = 'Mozilla';
+var empty = '';
+
+console.log('Mozilla는 코드 유닛 ' + x.length + '개의 길이입니다.');
+/* "Mozilla는 코드 유닛 7개의 길이입니다." */
+
+console.log('빈 문자열은 ' + empty.length + '의 길이를 가집니다.');
+/* "빈 문자열은 0의 길이를 가집니다." */
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.5.5.1', 'String.prototype.length')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-properties-of-string-instances-length', 'String.prototype.length')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-properties-of-string-instances-length', 'String.prototype.length')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.String.length")}}
+ +

같이 보기

+ + 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 +--- +
{{JSRef}}
+ +

The localeCompare() 메서드는 기준 문자열과 비교했을 때 비교 대상 문자열이 정렬상 전에 오는지, 후에 오는지 혹은 같은 순서에 배치되는지를 알려주는 숫자를 리턴합니다.

+ +

The new locales and options 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 locales and options arguments, the locale and sort order used are entirely implementation dependent.

+ +

Syntax

+ +
referenceStr.localeCompare(compareString[, locales[, options]])
+ +

Parameters

+ +

Check the Browser compatibility section to see which browsers support the locales and options arguments, and the Checking for support for locales and options arguments for feature detection.

+ +
+
compareString
+
The string against which the referring string is compared
+
+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Collator', 'Parameters')}}
+ +

Return value

+ +

A negative number if the reference string occurs before the compare string; positive if the reference string occurs after the compare string; 0 if they are equivalent.

+ +

Description

+ +

Returns an integer indicating whether the referenceStr comes before, after or is equivalent to the compareStr.

+ + + +

DO NOT rely on exact return values of -1 or 1. 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.

+ +

Examples

+ +

Using localeCompare()

+ +
// 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
+
+ +

Sort an array

+ +

localeCompare enables a case-insensitive sort of an array.

+ +
var items = ['réservé', 'premier', 'cliché', 'communiqué', 'café', 'adieu'];
+items.sort((a, b) => a.localeCompare(b)); // ['adieu', 'café', 'cliché', 'communiqué', 'premier', 'réservé']
+
+ +

Check browser support for extended arguments

+ +

The locales and options 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:

+ +
function localeCompareSupportsLocales() {
+  try {
+    'foo'.localeCompare('bar', 'i');
+  } catch (e) {
+    return e.name === 'RangeError';
+  }
+  return false;
+}
+
+ +

Using locales

+ +

The results provided by localeCompare() 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 locales argument:

+ +
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
+
+ +

Using options

+ +

The results provided by localeCompare() can be customized using the options argument:

+ +
// 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
+
+ +

Performance

+ +

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.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.5.4.9', 'String.prototype.localeCompare')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.localecompare', 'String.prototype.localeCompare')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.localecompare', 'String.prototype.localeCompare')}}{{Spec2('ESDraft')}} 
{{SpecName('ES Int 1.0', '#sec-13.1.1', 'String.prototype.localeCompare')}}{{Spec2('ES Int 1.0')}}locale and option parameter definitions.
{{SpecName('ES Int 2.0', '#sec-13.1.1', 'String.prototype.localeCompare')}}{{Spec2('ES Int 2.0')}} 
{{SpecName('ES Int Draft', '#sec-String.prototype.localeCompare', 'String.prototype.localeCompare')}}{{Spec2('ES Int Draft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.String.localeCompare")}}

+ +

See also

+ + 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 +--- +
{{JSRef}}
+ +
+ +

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

+ +

문법

+ +
str.match(regexp)
+ +

매개변수

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

결과 값

+ +

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

+ +

설명

+ +

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

+ +

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

+ +

이것도 보세요: RegExp 메서드

+ + + +

예제

+ +

match() 사용하기

+ +

다음 예제에서는, match()를 사용하여 'Chapter' 라는 단어와 그에 이어지는 1 이상의 숫자, 그리고 그에 이어서 소숫점, 숫자 형태가 반복되는 문자열을 찾는다. 이 정규표현식은 i 플래그를 사용함으로써, 대소문자 구분 없이 찾고자 하는 문자열을 찾는다.

+ +
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' 요소는 입력된 원래 문자열을 나타냄.
+ +

match()와 함께 글로벌(g) 및 대/소문자 무시(i) 플래그 사용하기

+ +

다음 예제는 글로벌(g) 및 대/소문자 무시(i) 플래그를 사용하여  match()를 사용하는 방법을 보여준다. A부터 E 까지의 모든 문자와 a부터 e 까지의 모든 문자가 배열의 각 원소를 구성하는 형태로 반환된다.

+ +
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']
+
+ +

매개변수 없이 match() 사용하기

+ +
var str = "Nothing will come of nothing.";
+
+str.match();   // returns [""]
+ +

정규표현식이 아닌 객체를 매개변수로 사용하기

+ +

매개변수가 문자열이나 숫자(Number)이면, 해당 매개변수는 내부적으로 new RegExp(obj)를 사용하여 {{jsxref("RegExp")}}로 변환된다. 만약 매개변수가 플러스 기호와 이어지는 숫자형이라면, RegExp() 매서드는 플러스 기호를 무시한다. 

+ +
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"]을 반환함.
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.5.4.10', 'String.prototype.match')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-string.prototype.match', 'String.prototype.match')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-string.prototype.match', 'String.prototype.match')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.String.match")}}

+ +

Firefox-specific notes

+ + + + + +

같이 보기

+ + 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 +--- +
{{JSRef}}
+ +

normalize() 메서드는 주어진 문자열을 유니코드 정규화 방식(Unicode Normalization Form)에 따라 정규화된 형태로 반환합니다. 만약 주어진 값이 문자열이 아닐 경우에는 우선 문자열로 변환 후 정규화합니다.

+ +
{{EmbedInteractiveExample("pages/js/string-normalize.html")}}
+ + + +

구문

+ +
str.normalize([form])
+ +

매개변수

+ +
+
form
+
유니코드 정규화 방식을 지정합니다. "NFC", "NFD", "NFKC""NFKD" 중 하나이며, 생략되거나 {{jsxref("undefined")}} 일 경우 "NFC"가 사용됩니다. +
    +
  • NFC — 정규형 정준 결합(Normalization Form Canonical Composition).
  • +
  • NFD — 정규형 정준 분해(Normalization Form Canonical Decomposition).
  • +
  • NFKC — 정규형 호환성 결합(Normalization Form Compatibility Composition).
  • +
  • NFKD — 정규형 호환성 분해(Normalization Form Compatibility Decomposition).
  • +
+
+
+ +

반환 값

+ +

주어진 문자열을 유니코드 정규화 방식에 따라 정규화된 문자열로 반환합니다.

+ +

예외

+ +
+
{{jsxref("RangeError")}}
+
form이 위에서 명시된 값 중 하나가 아닐 경우 {{jsxref("RangeError")}} 에러가 발생합니다.
+
+ +

설명

+ +

normalize() 메서드는 문자열을 유니코드 정규화 방식에 따라 정규화된 형태로 반환합니다. 문자열의 값 자체에는 영향을 주지 않습니다.

+ +

예제

+ +

normalize() 사용하기

+ +
// 원본 문자열
+
+// 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'
+
+ +

한글에 normalize() 사용하기

+ +
// 결합된 한글 문자열
+
+// 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를 출력합니다.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-string.prototype.normalize', 'String.prototype.normalize')}}{{Spec2('ES2015')}}초기 정의.
{{SpecName('ESDraft', '#sec-string.prototype.normalize', 'String.prototype.normalize')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.String.normalize")}}

+ +

같이 보기

+ + 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 +--- +
{{JSRef}}
+ +

padEnd() 메서드는 현재 문자열에 다른 문자열을 채워, 주어진 길이를 만족하는 새로운 문자열을 반환합니다. 채워넣기는 대상 문자열의 끝(우측)부터 적용됩니다.

+ +
{{EmbedInteractiveExample("pages/js/string-padend.html")}}
+ + + +

구문

+ +
str.padEnd(targetLength [, padString])
+ +

매개변수

+ +
+
targetLength
+
목표 문자열 길이. 현재 문자열의 길이보다 작다면 채워넣지 않고 그대로 반환.
+
padString {{optional_inline}}
+
현재 문자열에 채워넣을 다른 문자열. 문자열이 너무 길어 목표 문자열 길이를 초과한다면 좌측 일부를 잘라서 넣음. 기본값은 " ". (U+0020)
+
+ +

반환값

+ +

끝부터 주어진 문자열로 채워 목표 길이를 만족하는 {{jsxref("String")}}

+ +

예시

+ +
'abc'.padEnd(10);          // "abc       "
+'abc'.padEnd(10, "foo");   // "abcfoofoof"
+'abc'.padEnd(6, "123456"); // "abc123"
+'abc'.padEnd(1);           // "abc"
+ +

폴리필

+ +

다른 모든 코드 이전에 아래 코드를 포함하면 지원하지 않는 플랫폼에서도 String.prototype.padStart() 메서드를 사용할 수 있습니다.

+ +
// 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);
+        }
+    };
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-string.prototype.padend', 'String.prototype.padEnd')}}{{Spec2('ESDraft')}}Initial definition in ECMAScript 2017.
{{SpecName('ES8', '#sec-string.prototype.padend', 'String.prototype.padEnd')}}{{Spec2('ES8')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.String.padEnd")}}

+ +

See also

+ + 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 +--- +
{{JSRef}}
+ +

padStart() 메서드는 현재 문자열의 시작을 다른 문자열로 채워, 주어진 길이를 만족하는 새로운 문자열을 반환합니다. 채워넣기는 대상 문자열의 시작(좌측)부터 적용됩니다.

+ +

 

+ +
{{EmbedInteractiveExample("pages/js/string-padstart.html")}}
+ + + +

 

+ +

구문

+ +
str.padStart(targetLength [, padString])
+ +

매개변수

+ +
+
targetLength
+
목표 문자열 길이. 현재 문자열의 길이보다 작다면 채워넣지 않고 그대로 반환.
+
padString {{optional_inline}}
+
현재 문자열에 채워넣을 다른 문자열. 문자열이 너무 길어 목표 문자열 길이를 초과한다면 좌측 일부를 잘라서 넣음. 기본값은 " ". (U+0020)
+
+ +

반환값

+ +

시작점부터 주어진 문자열로 채워 목표 길이를 만족하는 {{jsxref("String")}}.

+ +

예시

+ +
'abc'.padStart(10);         // "       abc"
+'abc'.padStart(10, "foo");  // "foofoofabc"
+'abc'.padStart(6,"123465"); // "123abc"
+'abc'.padStart(8, "0");     // "00000abc"
+'abc'.padStart(1);          // "abc"
+ +

폴리필

+ +

다른 모든 코드 이전에 아래 코드를 포함하면 지원하지 않는 플랫폼에서도 String.prototype.padStart() 메서드를 사용할 수 있습니다.

+ +
// 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);
+        }
+    };
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-string.prototype.padstart', 'String.prototype.padStart')}}{{Spec2('ESDraft')}}Initial definition in ECMAScript 2017.
{{SpecName('ES8', '#sec-string.prototype.padstart', 'String.prototype.padStart')}}{{Spec2('ES8')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.String.padStart")}}

+ +

같이 보기

+ + 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 +--- +
{{JSRef("Global_Objects", "String")}}
+ +

요약

+ +

String.prototype 프라퍼티는 {{jsxref("Global_Objects/String", "String")}} 프로토타입 오브젝트를 표현하고 있습니다.

+ +
{{js_property_attributes(0, 0, 0)}}
+ +

설명

+ +

모든 {{jsxref("Global_Objects/String", "String")}} 인스턴스들은 String.prototype를 상속합니다. String 프라퍼티 오브젝트를 변경하면, 그 변경은 모든 {{jsxref("Global_Objects/String", "String")}} 인스턴스들에 영향을 주게 됩니다.

+ +

Properties

+ +
+
String.prototype.constructor
+
오브젝트의 프로토타입을 생성하는 함수를 명세합니다.
+
{{jsxref("String.prototype.length")}}
+
문자열의 길이를 반영합니다.
+
N
+
N번째 위치에 있는 문자에 접근하기 위해 사용합니다.  N 은 0과 {{jsxref("String.length", "length")}}보다 작은 값 사이에 있는 양의 정수입니다. 이 퍼라퍼티들은 읽기 전용(read-only) 속성을 가지고 있습니다. 
+
+ +

메서드

+ +

HTML과 관련이 없는 메서드

+ +
+
{{jsxref("String.prototype.charAt()")}}
+
문자열 내 특정 위치(index)에 있는 문자를 반환합니다.
+
{{jsxref("String.prototype.charCodeAt()")}}
+
문자열 내 주어진 위치(index)에 있는 문자의 유니코드 값을 반환합니다.
+
{{jsxref("String.prototype.codePointAt()")}} {{experimental_inline}}
+
주어진 위치에 있는 UTF-16으로 인코딩된 코드 포인터값인 음수가 아닌 정수값을 반환합니다. 
+
{{jsxref("String.prototype.concat()")}}
+
두 문자열의 문자를 합쳐서 새로운 문자열로 만든 다음, 그 새로운 문자열을 반환합니다. 
+
{{jsxref("String.prototype.includes()")}} {{experimental_inline}}
+
문자열 내에 찾고자 하는 문자열이 있는지를 확인합니다. 
+
{{jsxref("String.prototype.endsWith()")}} {{experimental_inline}}
+
문자열에서 특정 문자열로 끝나는지를 확인할 수 있습니다.
+
{{jsxref("String.prototype.indexOf()")}}
+
{{jsxref("Global_Objects/String", "String")}} 오브젝트에 있는 특정 값이 일치하는 첫 번째 인덱스 값을 반환하며, 일치하는 값이 없을 경우에는 -1을 반환합니다.
+
{{jsxref("String.prototype.lastIndexOf()")}}
+
String 오브젝트에서 fromIndex로부터 반대방향으로 찾기 시작하여 특정 값이 일치하는 마지막 인덱스를 반환합니다. 문자열에서 일치하는 특정 값이 없으면 -1을 리턴합니다.
+
{{jsxref("String.prototype.localeCompare()")}}
+
Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.
+
{{jsxref("String.prototype.match()")}}
+
Used to match a regular expression against a string.
+
{{jsxref("String.prototype.normalize()")}} {{experimental_inline}}
+
Returns the Unicode Normalization Form of the calling string value.
+
{{jsxref("String.prototype.quote()")}} {{obsolete_inline}}
+
Wraps the string in double quotes (""").
+
{{jsxref("String.prototype.repeat()")}} {{experimental_inline}}
+
Returns a string consisting of the elements of the object repeated the given times.
+
{{jsxref("String.prototype.replace()")}}
+
Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring.
+
{{jsxref("String.prototype.search()")}}
+
Executes the search for a match between a regular expression and a specified string.
+
{{jsxref("String.prototype.slice()")}}
+
Extracts a section of a string and returns a new string.
+
{{jsxref("String.prototype.split()")}}
+
Splits a {{jsxref("Global_Objects/String", "String")}} object into an array of strings by separating the string into substrings.
+
{{jsxref("String.prototype.startsWith()")}} {{experimental_inline}}
+
Determines whether a string begins with the characters of another string.
+
{{jsxref("String.prototype.substr()")}}
+
Returns the characters in a string beginning at the specified location through the specified number of characters.
+
{{jsxref("String.prototype.substring()")}}
+
Returns the characters in a string between two indexes into the string.
+
{{jsxref("String.prototype.toLocaleLowerCase()")}}
+
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()")}}.
+
{{jsxref("String.prototype.toLocaleUpperCase()")}}
+
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()")}}.
+
{{jsxref("String.prototype.toLowerCase()")}}
+
Returns the calling string value converted to lower case.
+
{{jsxref("String.prototype.toSource()")}} {{non-standard_inline}}
+
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.
+
{{jsxref("String.prototype.toString()")}}
+
Returns a string representing the specified object. Overrides the {{jsxref("Object.prototype.toString()")}} method.
+
{{jsxref("String.prototype.toUpperCase()")}}
+
Returns the calling string value converted to uppercase.
+
{{jsxref("String.prototype.trim()")}}
+
Trims whitespace from the beginning and end of the string. Part of the ECMAScript 5 standard.
+
{{jsxref("String.prototype.trimLeft()")}} {{non-standard_inline}}
+
Trims whitespace from the left side of the string.
+
{{jsxref("String.prototype.trimRight()")}} {{non-standard_inline}}
+
Trims whitespace from the right side of the string.
+
{{jsxref("String.prototype.valueOf()")}}
+
Returns the primitive value of the specified object. Overrides the {{jsxref("Object.prototype.valueOf()")}} method.
+
{{jsxref("String.prototype.@@iterator()", "String.prototype[@@iterator]()")}} {{experimental_inline}}
+
Returns a new Iterator object that iterates over the code points of a String value, returning each code point as a String value.
+
+ +

HTML wrapper methods

+ +

These methods are of limited use, as they provide only a subset of the available HTML tags and attributes.

+ +
+
{{jsxref("String.prototype.big()")}} {{deprecated_inline}}
+
{{HTMLElement("big")}}
+
{{jsxref("String.prototype.blink()")}} {{deprecated_inline}}
+
{{HTMLElement("blink")}}
+
{{jsxref("String.prototype.bold()")}} {{deprecated_inline}}
+
{{HTMLElement("b")}}
+
{{jsxref("String.prototype.fixed()")}} {{deprecated_inline}}
+
{{HTMLElement("tt")}}
+
{{jsxref("String.prototype.fontcolor()")}} {{deprecated_inline}}
+
{{htmlattrxref("color", "font", "<font color=\"color\">")}}
+
{{jsxref("String.prototype.fontsize()")}} {{deprecated_inline}}
+
{{htmlattrxref("size", "font", "<font size=\"size\">")}}
+
{{jsxref("String.prototype.italics()")}} {{deprecated_inline}}
+
{{HTMLElement("i")}}
+
{{jsxref("String.prototype.link()")}}
+
{{htmlattrxref("href", "a", "<a href=\"rul\">")}} (link to URL)
+
{{jsxref("String.prototype.small()")}} {{deprecated_inline}}
+
{{HTMLElement("small")}}
+
{{jsxref("String.prototype.strike()")}} {{deprecated_inline}}
+
{{HTMLElement("strike")}}
+
{{jsxref("String.prototype.sub()")}} {{deprecated_inline}}
+
{{HTMLElement("sub")}}
+
{{jsxref("String.prototype.sup()")}} {{deprecated_inline}}
+
{{HTMLElement("sup")}}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
ECMAScript 1st Edition.StandardInitial definition.
{{SpecName('ES5.1', '#sec-15.5.3.1', 'String.prototype')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-string.prototype', 'String.prototype')}}{{Spec2('ES6')}}
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + 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 +--- +
{{JSRef}}
+ +

repeat() 메서드는 문자열을 주어진 횟수만큼 반복해 붙인 새로운 문자열을 반환합니다.

+ +

구문

+ +
str.repeat(count);
+ +

매개변수

+ +
+
count
+
문자열을 반복할 횟수. 0과 양의 무한대 사이의 정수([0, +∞)).
+
+ +

반환값

+ +

현재 문자열을 주어진 횟수만큼 반복해 붙인 새로운 문자열.

+ +

예외

+ + + +

예제

+ +
'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)
+
+ +

폴리필

+ +

repeat은 ECMAScript 2015 명세에 추가됐습니다. 따라서 어떤 표준 구현체에서는 사용할 수 없을 수도 있습니다. 그러나 아래 코드를 포함하면 지원하지 않는 플랫폼에서도 repeat을 사용할 수 있습니다.

+ +
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;
+  }
+}
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-string.prototype.repeat', 'String.prototype.repeat')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-string.prototype.repeat', 'String.prototype.repeat')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.String.repeat")}}

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 +--- +
{{JSRef}}
+ +

replace() 메서드는 어떤 패턴에 일치하는 일부 또는 모든 부분이 교체된 새로운 문자열을 반환합니다. 그 패턴은 문자열이나 정규식({{jsxref("RegExp")}})이 될 수 있으며, 교체 문자열은 문자열이나 모든 매치에 대해서 호출된 함수일 수 있습니다.

+ +

 

+ +

pattern이 문자열 인 경우, 첫 번째 문자열만 치환이 되며 원래 문자열은 변경되지 않습니다.

+ +

{{EmbedInteractiveExample("pages/js/string-replace.html")}}

+ +

구문

+ +
var newStr = str.replace(regexp|substr, newSubstr|function)
+ +

매개변수

+ +
+
regexp (pattern)
+
정규식({{jsxref ( "RegExp")}}) 객체 또는 리터럴. 일치하는 항목은 newSubStr 또는 지정된 함수(function)가 반환 한 값으로 대체됩니다.
+
substr (pattern)
+
newSubStr로 대체 될 {{jsxref ( "String")}}. 정규식이 아닌 글자 그대로의 문자열로 처리됩니다. 오직 첫 번째 일치되는 문자열만이 교체됩니다.
+
newSubStr (replacement)
+
첫번째 파라미터를 대신할 문자열({{jsxref("String")}}). 여러가지 대체 패턴들이 지원됩니다. 아래의 "매개변수가 string으로 지정되었을 때" 섹션을 참고하세요.
+
function (replacement)
+
주어진 regexp 또는 substr에 일치하는 요소를 대체하는 데 사용될 새 하위 문자열을 생성하기 위해 호출되는 함수. 이 함수에 제공되는 인수는 아래 "매개변수가 function으로 지정되었을 때"단원에서 설명합니다.
+
+ +

반환값

+ +

어떤 패턴에 일치하는 일부 또는 모든 부분이 교체된 새로운 문자열

+ +

설명

+ +

이 메서드는 호출된 {{jsxref("String")}} 객체를 바꾸지 않습니다. 단순히 새로운 문자열을 리턴합니다.

+ +

모든 문자열에 대해 검색하고 바꾸려면 정규표현식의 g플래그를 포함하세요.

+ +

매개변수가 string으로 지정되었을 때

+ +

replacement 문자열은 다음과 같은 특수 교체 패턴을 포함할 수 있습니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PatternInserts
$$ "$" 기호를 삽입합니다.
$&매치된 문자열을 삽입합니다.
$`매치된 문자열 앞쪽까지의 문자열을 삽입합니다.
$'매치된 문자열의 문자열을 삽입합니다.
$n +

n이 1이상 99이하의 정수라면, 첫번째 매개변수로 넘겨진 {{jsxref("RegExp")}}객체에서 소괄호로 묶인 n번째의 부분 표현식으로 매치된 문자열을 삽입합니다.

+
+ +

매개변수가 function으로 지정되었을 때

+ +

두번째 매개변수로 함수를 지정할 수 있습니다. 이 경우, 함수는 정규표현식 매치가 수행된 후 호출될 것입니다. 함수의 반환값은 교체될 문자열이 됩니다. (참고: 윗쪽에서 언급된 특수 교체 패턴은 반환값에 적용되지 않습니다.) 만약 정규표현식의 플래그로 글로벌(g)이 오는 경우, 함수는 매치될 때마다 계속 호출될 것입니다. 

+ +

함수의 매개변수들은 다음과 같습니다.

+ + + + + + + + + + + + + + + + + + + + + + + + +
Possible nameSupplied value
match매치된 문자열. (윗쪽의 $& 표현식으로 매치된 경우와 동일합니다.)
p1,
+ p2,
+ ...
윗쪽의 $n 표현식과 동일합니다. ($1p1, $2p2...) 예를 들어, 만약 정규표현식 /(\a+)(\b+)/ 이 주어진다면 p1\a+와 매치되고 p2\b+와 매치됩니다.
offset조사된 전체 문자열 중에서 매치된 문자열의 index.(예를 들어, 조사될 전체 문자열이 abcd이고, 매치된 문자열이 bc면 이 매개변수의 값은 1이 됩니다.)
string조사된 전체 문자열 (replace를 호출한 string)
+ +

인수의 정확한 수는 첫 번째 인수가 {{jsxref ( "RegExp")}} 객체인지 아닌지에 따라 다르며, 소괄호로 묶이는 부분표현식의 갯수에 따라 달라집니다.

+ +

 

+ +

다음 예제는 newString을 'abc - 12345 - #$*%'로 교체합니다:

+ +
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 - #$*%
+ +

예제

+ +

replace()의 정규표현식 정의

+ +

다음 예제에서, 대소문자를 구분하지 않는 정규표현식을 replace()에 정의했습니다.

+ +
var str = 'Twas the night before Xmas...';
+var newstr = str.replace(/xmas/i, 'Christmas');
+console.log(newstr);  // Twas the night before Christmas...
+
+ +

'Twas the night before Christmas...'로 출력됩니다.

+ +

global과 ignore를 사용한 replace()

+ +

Global replace는 정규식으로만 수행 할 수 있습니다. 다음 예제에서 정규 표현식은 replace()가 'apples'를 'oranges'로 바꿀 수 있도록 global 및 ignore case 플래그를 포함합니다.

+ +
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.
+
+ +

'오렌지는 둥글고 오렌지는 맛있습니다.' 가 출력됩니다.

+ +

 

+ +

문자열의 단어 치환

+ +

다음 스크립트는 문자열의 단어를 전환합니다. 대체 텍스트의 경우 스크립트는 $1$2 대체 패턴을 사용합니다.

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

'Smith, John.'이 출력됩니다.

+ +

Using an inline function that modifies the matched characters

+ +

 

+ +

이 예제에서 문자열의 대문자가 모두 소문자로 변환되고 일치되는 위치 바로 앞에 하이픈이 삽입됩니다. 여기에서 중요한 점은 일치되는 항목이 대체 항목으로 다시 반환되기 전에 추가 작업이 필요하다는 것입니다.

+ +

바꾸기 기능은 일치하는 스니펫을 매개 변수로 받고 이를 사용하여 각 케이스별로 변환한후 반환하기 전에 하이픈을 연결합니다.

+ +

 

+ +
function styleHyphenFormat(propertyName) {
+  function upperToHyphenLower(match) {
+    return '-' + match.toLowerCase();
+  }
+  return propertyName.replace(/[A-Z]/g, upperToHyphenLower);
+}
+
+ +

Given styleHyphenFormat('borderTop'), this returns 'border-top'.

+ +

Because we want to further transform the result 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.

+ +
var newString = propertyName.replace(/[A-Z]/g, '-' + '$&'.toLowerCase());  // won't work
+
+ +

This is because '$&'.toLowerCase() would be evaluated first as a string literal (resulting in the same '$&') before using the characters as a pattern.

+ +

Replacing a Fahrenheit degree with its Celsius equivalent

+ +

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.

+ +

The regular expression test checks for any number that ends with F. The number of Fahrenheit degree is accessible to the function through its second parameter, p1. The function sets the Celsius number based on the Fahrenheit degree passed in a string to the f2c() function. f2c() then returns the Celsius number. This function approximates Perl's s///e flag.

+ +
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);
+}
+
+ +

Use an inline function with a regular expression to avoid for loops

+ +

The following example takes a string pattern and converts it into an array of objects.

+ +

Input:

+ +

A string made out of the characters x, - and _

+ +
x-x_
+x---x---x---x---
+x-xxx-xx-x-
+x_x_x___x___x___
+
+ +

Output:

+ +

An array of objects. An 'x' denotes an 'on' state, a '-' (hyphen) denotes an 'off' state and an '_' (underscore) denotes the length of an 'on' state.

+ +
[
+  { on: true, length: 1 },
+  { on: false, length: 1 },
+  { on: true, length: 2 }
+  ...
+]
+
+ +

Snippet:

+ +
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);
+
+ +

This snippet generates an array of 3 objects in the desired format without using a for loop.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.5.4.11', 'String.prototype.replace')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.replace', 'String.prototype.replace')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.replace', 'String.prototype.replace')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
 
+ +
{{Compat("javascript.builtins.String.replace")}}
+ +

Firefox-specific notes

+ + + +

같이 보기

+ + 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 +--- +
{{JSRef}}
+ +

search() 메서드는 정규 표현식과  이 {{jsxref("String")}}  객체간에 같은 것을 찾기
+ 위한 검색을 실행한다.

+ +
{{EmbedInteractiveExample("pages/js/string-search.html")}}
+ + + +

구문

+ +
str.search(regexp)
+ +

매개변수

+ +
+
regexp
+
정규 표현식 객체.  non-RegExp 객체 obj 가 전달되면,  그것은  new RegExp(obj) 을 이용하여 {{jsxref("RegExp")}} 으로 암묵적으로 변환된다.
+
+ +

반환 값

+ +

정규표현식과 주어진 스트링간에 첫번째로 매치되는 것의 인덱스를 반환한다.
+ 찾지 못하면 -1 를 반환한다.

+ +

설명

+ +

When you want to know whether a pattern is found and also its index in a string use search() (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).

+ +

+ +

search()를 이용하기

+ +

The following example searches a string with 2 different regex objects to show a successful search (positive value) vs. an unsuccessful search (-1)

+ +
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
+ +

사양

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
사양상태주석
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.5.4.12', 'String.prototype.search')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.search', 'String.prototype.search')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.search', 'String.prototype.search')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.String.search")}}

+ +

Gecko-specific notes

+ + + +

See also

+ + 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 +--- +
{{JSRef}}
+ +

slice() 메소드는 문자열의 일부를 추출하면서 새로운 문자열을 반환합니다.

+ +

{{EmbedInteractiveExample("pages/js/string-slice.html")}}

+ +

문법

+ +
str.slice(beginIndex[, endIndex])
+ +

매개변수

+ +
+
beginIndex
+
추출 시작점인 0부터 시작하는 인덱스입니다. 만약 음수라면, beginIndex는  strLength(문자열 길이) + beginIndex로 취급됩니다. (예를 들어 beginIndex가 -3이면 시작점은 strLength - 3).
+
만약 beginIndex가 strLength 보다 크거나 같은 경우, slice()는 빈 문자열을 반환합니다.
+
endIndex{{optional_inline}}
+
0부터 시작하는 추출 종료점 인덱스로 그 직전까지 추출됩니다.  인덱스 위치의 문자는 추출에 포함되지 않습니다.
+
만약 endIndex가 생략된다면, silce()는 문자열 마지막까지 추출합니다. 만약 음수라면, endIndex는 strLength(문자열 길이) + endIndex 로 취급됩니다(예를 들어 endIndex가 -3이면 종료점은 strLength - 3).
+
+ +

반환 값

+ +

문자열의 추출된 부분을 담는 새로운 문자열이 반환됩니다.

+ +

설명

+ +

slice()는 문자열로부터 텍스트를 추출하고 새 문자열을 반환합니다. 문자열의 변경은 다른 문자열에 영향을 미치지 않습니다.

+ +

slice()endIndex를 포함하지 않고 추출합니다. str.slice(1, 4)는 두 번째 문자부터 네 번째 문자까지 추출합니다 (1, 2, 3 인덱스 문자).

+ +

str.slice(2, -1)는 세 번째 문자부터 문자열의 마지막에서 두 번째 문자까지 추출합니다.

+ +

예시

+ +

slice()를 사용하여 새 문자열 생성하기

+ +

아래 예시는 새 문자열을 생성하기 위해 slice()를 사용합니다.

+ +
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: ""
+
+ +

음수 인덱스로 slice() 사용하기

+ +

아래 예시는 slice()에 음수 인덱스를 사용합니다.

+ +
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'
+
+ +

아래의 예시는 시작 인덱스를 찾기 위해 문자열의 끝에서부터 역방향으로 11개를 세고 끝 인덱스를 찾기 위해 문자열의 시작에서부터 정방향으로 16개를 셉니다.

+ +
console.log(str.slice(-11, 16)) // => "is u";
+ +

아래에서는 시작 인덱스를 찾기 위해 문자열의 처음부터 정방향으로 11개를 세고 끝 인덱스를 찾기 위해 끝에서부터 7개를 셉니다.

+ +
console.log(str.slice(11, -7)) // => "is u";
+
+ +

이 인수는 끝에서부터 5로 역순으로 계산하여 시작 인덱스를 찾은 다음 끝에서부터 1을 거쳐 끝 인덱스를 찾습니다.

+ +
console.log(str.slice(-5, -1)) // => "n us";
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-string.prototype.slice', 'String.prototype.slice')}}{{Spec2('ESDraft')}}
{{SpecName('ES6', '#sec-string.prototype.slice', 'String.prototype.slice')}}{{Spec2('ES6')}}
{{SpecName('ES5.1', '#sec-15.5.4.13', 'String.prototype.slice')}}{{Spec2('ES5.1')}}
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
+ +

Browser compatibility

+ +

{{Compat("javascript.builtins.String.slice")}}

+ +

See also

+ + 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 +--- +
{{JSRef}}
+ +

split() 메서드는 {{jsxref("String")}} 객체를 지정한 구분자를 이용하여 여러 개의 문자열로 나눕니다.

+ +
{{EmbedInteractiveExample("pages/js/string-split.html")}}
+ + + +

구문

+ +
str.split([separator[, limit]])
+ +
+

주의: 구분자로 빈 문자열("")을 제공하면, 사용자가 인식하는 문자 하나(grapheme cluster) 또는 유니코드 문자(코드포인트) 하나씩으로 나누는 것이 아니라, UTF-16 코드유닛으로 나누게 되며 써로게이트 페어surrogate pair가 망가질 수 있습니다. 스택 오버플로우의 How do you get a string to a character array in JavaScript? 질문도 참고해 보세요.

+
+ +

매개변수

+ +
+
separator {{optional_inline}}
+
원본 문자열을 끊어야 할 부분을 나타내는 문자열을 나타냅니다. 실제 문자열이나 {{jsxref("Global_Objects/RegExp", "정규표현식", "", 1)}}을 받을 수 있습니다. 문자열 유형의 separator가 두 글자 이상일 경우 그 부분 문자열 전체가 일치해야 끊어집니다. separator가 생략되거나 str에 등장하지 않을 경우, 반환되는 배열은 원본 문자열을 유일한 원소로 가집니다. separator가 빈 문자열일 경우 str의 각각의 문자가 배열의 원소 하나씩으로 변환됩니다.
+
limit {{optional_inline}}
+
+

끊어진 문자열의 최대 개수를 나타내는 정수입니다. 이 매개변수를 전달하면 split() 메서드는 주어진 separator가 등장할 때마다 문자열을 끊지만 배열의 원소가 limit개가 되면 멈춥니다. 지정된 한계에 도달하기 전에 문자열의 끝까지 탐색했을 경우 limit개 미만의 원소가 있을 수도 있습니다. 남은 문자열은 새로운 배열에 포함되지 않습니다.

+
+
+ +

반환값

+ +

주어진 문자열을 separator마다 끊은 부분 문자열을 담은 {{jsxref("Array")}}.

+ +

설명

+ +

문자열에서 separator가 등장하면 해당 부분은 삭제되고 남은 문자열이 배열로 반환됩니다. separator가 등장하지 않거나 생략되었을 경우 배열은 원본 문자열을 유일한 원소로 가집니다. separator가 빈 문자열일 경우, str은 문자열의 모든 문자를 원소로 가지는 배열로 변환됩니다. separator가 원본 문자열의 처음이나 끝에 등장할 경우 반환되는 배열도 빈 문자열로 시작하거나 끝납니다. 그러므로 원본 문자열에 separator 하나만이 포함되어 있을 경우 빈 문자열 두 개를 원소로 가지는 배열이 반환됩니다.

+ +

separator가 포획 괄호capturing parentheses를 포함하는 정규표현식일 경우, separator가 일치할 때마다 포획 괄호의 (정의되지 않은 경우도 포함한) 결과가 배열의 해당 위치에 포함됩니다.

+ +

{{Note("separator가 배열일 경우 분할에 사용하기 전에 우선 문자열로 변환됩니다.")}}

+ +

예제

+ +

split() 사용하기

+ +

{{Note("빈 문자열이 주어졌을 경우 split()은 빈 배열이 아니라 빈 문자열을 포함한 배열을 반환합니다. 문자열과 separator가 모두 빈 문자열일 때는 빈 배열을 반환합니다.")}}

+ +
const myString = '';
+const splits = myString.split();
+
+console.log(splits);
+
+// ↪ [""]
+
+ +

다음 예제에서는 문자열을 주어진 구분자로 끊는 함수를 정의합니다. 문자열을 끊은 다음에는 (끊기 이전의) 원본 문자열과 사용한 구분자, 배열의 길이와 각 원소를 로그로 출력합니다.

+ +
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);
+
+ +

위 예제의 출력은 다음과 같습니다.

+ +
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
+
+ +

문자열에서 공백 제거하기

+ +

다음 예제에서 split()은 세미콜론 앞뒤에 각각 0개 이상의 공백이 있는 부분 문자열을 찾고, 있을 경우 문자열에서 세미콜론과 공백을 제거합니다. split()의 결과로 반환된 배열은  nameList에 저장됩니다.

+ +
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);
+
+ +

위 예제는 원본 문자열과 반환된 배열을 각각 한 줄씩 로그로 출력합니다.

+ +
Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand
+[ "Harry Trump", "Fred Barney", "Helen Rigby", "Bill Abel", "Chris Hand", "" ]
+
+ +

끊는 횟수 제한하기

+ +

다음 예제에서 split()은 문자열을 공백으로 끊고 처음 3개의 문자열을 반환합니다.

+ +
var myString = 'Hello World. How are you doing?';
+var splits = myString.split(' ', 3);
+
+console.log(splits);
+
+ +

위 예제의 로그 출력은 다음과 같습니다.

+ +
["Hello", "World.", "How"]
+
+ +

RegExp를 사용해 구분자도 결과에 포함하기

+ +

separator가 포획 괄호 ()를 포함하는 정규표현식일 경우, 포획된 결과도 배열에 포함됩니다.

+ +
var myString = 'Hello 1 word. Sentence number 2.';
+var splits = myString.split(/(\d)/);
+
+console.log(splits);
+
+ +

위 예제의 로그 출력은 다음과 같습니다.

+ +
[ "Hello ", "1", " word. Sentence number ", "2", "." ]
+
+ +

배열을 구분자로 사용하기

+ +
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']);
+// myString.split(['a','b'])myString.split(String(['a','b']))와 같다
+
+console.log(splits);  //["c", "c,", "c", "c", "c"]
+
+ +

split()으로 문자열 뒤집기

+ +
+

이 방법은 문자열 뒤집기에 효과적인 방법이 아닙니다.

+ +
var str = 'asdfghjkl';
+var strReverse = str.split('').reverse().join(''); // 'lkjhgfdsa'
+// split()에서 반환한 배열에는 reverse()와 join()을 사용할 수 있다
+
+ +

문자열에 grapheme clusters가 있을 경우, 유니코드 플래그를 설정해도 오류를 일으킵니다(esrever 등의 라이브러리를 대신 사용하세요).

+ +
var str = 'résumé';
+var strReverse = str.split(/(?:)/u).reverse().join('');
+// => "́emuśer"
+
+ +

추가: {{jsxref("Operators/Comparison_Operators", "===", "#Identity_strict_equality_(===)")}} 연산자를 사용하면 원본 문자열이 팰린드롬인지 확인할 수 있습니다.

+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태비고
{{SpecName('ES3')}}{{Spec2('ES3')}}초기 정의. JavaScript 1.1에 구현되었음.
{{SpecName('ES5.1', '#sec-15.5.4.14', 'String.prototype.split')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-string.prototype.split', 'String.prototype.split')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-string.prototype.split', 'String.prototype.split')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.String.split")}}

+ +

같이 보기

+ + 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 +--- +
{{JSRef}}
+ +

startsWith() 메소드는 어떤 문자열이 특정 문자로 시작하는지 확인하여 결과를 true 혹은 false로 반환합니다.

+ +

구문

+ +
str.startsWith(searchString[, position])
+ +

매개변수

+ +
+
searchString
+
문자열의 시작 지점에서 탐색할 문자열
+
position {{optional_inline}}
+
searchString을 탐색할 위치. 기본값 0.
+
+ +

반환 값

+ +

문자열이 검색 문자열로 시작하면 true, 아니면 false.

+ +

  설명

+ +

startsWith 메소드로 어떤 문자열이 다른 문자열로 시작하는지 확인 할 수 있습니다. 대소문자를 구분합니다.

+ +

예시

+ +

startsWith() 사용하기

+ +
//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
+
+ +

폴리필

+ +

startsWith 메소드는 ECMAScript 2015 명세에 포함됐으며, 아직까지 모든 JavaScrpt 구현체가 지원하지 않을 수 있습니다. 그러나 아래 코드 조각을 사용해 폴리필 할 수 있습니다.

+ +
if (!String.prototype.startsWith) {
+	String.prototype.startsWith = function(search, pos) {
+		return this.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
+	};
+}
+ +

ES2015 명세를 모두 만족하지만, 더 무거운 폴리필은 Mathias Bynens의 GitHub 에서 확인할 수 있습니다.

+ +

명세서

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-string.prototype.startswith', 'String.prototype.startsWith')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-string.prototype.startswith', 'String.prototype.startsWith')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.String.startsWith")}}
+ +

관련 문서

+ + 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 +--- +
{{JSRef}}
+ +
 
+ +
+

경고: 엄밀히 말해서 String.prototype.substr() 메서드가 더 이상 사용되지 않는, 즉 "웹 표준에서 제거된" 건 아닙니다. 그러나 substr()이 포함된 ECMA-262 표준의 부록 B는 다음과 같이 명시하고 있습니다.

+ +
… 본 부록이 포함한 모든 언어 기능과 행동은 하나 이상의 바람직하지 않은 특징을 갖고 있으며 사용처가 없어질 경우 명세에서 제거될 것입니다. …
+… 프로그래머는 새로운 ECMAScript 코드를 작성할 때 본 부록이 포함한 기능을 사용하거나 존재함을 가정해선 안됩니다. …
+
+ +

substr() 메서드는 문자열에서 특정 위치에서 시작하여 특정 문자 수 만큼의 문자들을 반환합니다.

+ +

{{EmbedInteractiveExample("pages/js/string-substr.html")}}

+ +

구문

+ +
str.substr(start[, length])
+ +

매개변수

+ +
+
start
+
추출하고자 하는 문자들의 시작위치입니다. 만약 음수가 주어진다면, 문자열총길이 + start의 값으로 취급합니다. 예를 들면, start에 -3을 설정하면, 자동적으로 문자열총길이 - 3으로 설정하게 됩니다. 
+
length
+
옵션값. 추출할 문자들의 총 숫자.
+
+ +

설명

+ +

start는 문자 인덱스입니다. 문자열에서 첫 번째 문자의 인덱스는 0이며, 마지막 문자의 인덱스는 문자열 전체 길이에서 1을 뺀 값입니다. substr() start에서 문자들을 추출을 시작하여 length만큼 문자들을 수집합니다.

+ +

만약 start 값이 양수이고 문자열 전체 길이보다 크거가 같을 경우, substr()은 빈 문자열을 반환합니다. 

+ +

만약 start가 음수이면, substr()은 문자열 끝에서 start 숫자만큼 뺀 곳에서 시작하게 됩니다. 만약 start가 음수이고 절대값이 문자열 전체보다 크다면, substr()은 문자열의 0 인덱스부터 시작하게 됩니다. (주의: start의 음수값은 Microsoft JScript에서는 위의 설명과 같이 동작하지 않습니다.)

+ +

만약 length가 0 혹은 음수이면, substr()은 빈 문자열을 반환합니다. 만약 length가 생략되면, substr()은 문자열의 끝까지 추출하여 반환합니다. 

+ +

예제

+ +

substr() 사용하기

+ +
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): '
+
+ +

폴리필

+ +

Microsoft의 JScript는 시작 인덱스에서 음수값을 지원하지 않습니다. 만약 여러분이 이렇게 동작하길 원한다면, 아래 코드를 사용하여 해결할 수 있습니다: 

+ +
// 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);
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Defined in the (informative) Compatibility Annex B. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-B.2.3', 'String.prototype.substr')}}{{Spec2('ES5.1')}}Defined in the (informative) Compatibility Annex B
{{SpecName('ES6', '#sec-string.prototype.substr', 'String.prototype.substr')}}{{Spec2('ES6')}}Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers
{{SpecName('ESDraft', '#sec-string.prototype.substr', 'String.prototype.substr')}}{{Spec2('ESDraft')}}Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.String.substr")}}
+ +

같이 보기

+ + 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 +--- +
{{JSRef}}
+ +

substring()메소드는 string 객체의 시작 인덱스로 부터 종료 인덱스 전 까지 문자열의 부분 문자열을 반환합니다. 

+ +
{{EmbedInteractiveExample("pages/js/string-substring.html")}}
+ + + +

사용방법 

+ +
str.substring(indexStart[, indexEnd])
+ +

인자값

+ +
+
indexStart
+
반환문자열의 시작 인덱스 
+
 
+
indexEnd
+
옵션.  반환문자열의 마지막 인덱스 (포함하지 않음.)
+
+ +

반환값

+ +

기존문자열의  부분 문자열을 반환합니다. 

+ +

Description

+ +

substring() 메서드는 indexStart 부터 문자를 추출하지만 indexEnd 가 포함되지 않아도 괜찮습니다. 특징은 아래와 같습니다.

+ + + +

0보다 작은 인자 값을 가지는 경우에는 0으로, stringName.length 보다 큰 인자 값을 가지는 경우, stringName.length 로 처리됩니다. {{jsxref("NaN")}} 값은 0으로 처리됩니다.

+ +

Examples

+ +

Using substring()

+ +

The following example uses substring() to display characters from the string 'Mozilla':

+ +
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));
+
+ +

Using substring() with length property

+ +

The following example uses the substring() 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.

+ +
// 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);
+
+ +

The difference between substring() and substr()

+ +

There's a subtle difference between the substring() and {{jsxref("String.substr", "substr()")}} methods, so you should be careful not to get them confused.

+ +

The arguments of substring() represent the starting and ending indexes, while the arguments of substr() represent the starting index and the number of characters to include in the returned string.

+ +
var text = 'Mozilla';
+console.log(text.substring(2,5)); // => "zil"
+console.log(text.substr(2,3));    // => "zil"
+ +

Differences between substring() and slice()

+ +

The substring() 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.

+ +

The substring() method swaps its two arguments if indexStart is greater than indexEnd, meaning that a string is still returned. The {{jsxref("String.slice", "slice()")}} method returns an empty string if this is the case.

+ +
var text = 'Mozilla';
+console.log(text.substring(5, 2)); // => "zil"
+console.log(text.slice(5, 2));     // => ""
+
+ +

If either or both of the arguments are negative or NaN, the substring() method treats them as if they were 0.

+ +
console.log(text.substring(-5, 2)); // => "Mo"
+console.log(text.substring(-5, -2)); // => ""
+
+ +

slice() also treats NaN arguments as 0, but when it is given negative values it counts backwards from the end of the string to find the indexes.

+ +
console.log(text.slice(-5, 2)); // => ""
+console.log(text.slice(-5, -2)); // => "zil"
+
+ +

See the {{jsxref("String.slice", "slice()")}} page for more examples with negative numbers.

+ +

Replacing a substring within a string

+ +

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 Brave New World to Brave New Web.

+ +
// 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');
+
+ +

Note that this can result in an infinite loop if oldS is itself a substring of newS — for example, if you attempted to replace 'World' with 'OtherWorld' here. A better method for replacing strings is as follows:

+ +
function replaceString(oldS, newS, fullS) {
+  return fullS.split(oldS).join(newS);
+}
+
+ +

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()")}}.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-string.prototype.substring', 'String.prototype.substring')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-string.prototype.substring', 'String.prototype.substring')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-15.5.4.15', 'String.prototype.substring')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1')}}{{Spec2('ES1')}}Implemented in JavaScript 1.0.
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.String.substring")}}

+ +

See also

+ + 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 +--- +
{{JSRef}}
+ +
toLowerCase() 메서드는 문자열을 소문자로 변환해 반환합니다.
+ +
 
+ +
{{EmbedInteractiveExample("pages/js/string-tolowercase.html")}}
+ +

구문

+ +
str.toLowerCase()
+ +

반환값

+ +

호출 문자열을 소문자로 변환한 새로운 문자열

+ +

설명

+ +

toLowerCase() 메서드는 호출 문자열을 소문자로 변환해 반환합니다.  toLowerCase() 는 원래의 str에 영향을 주지 않습니다.

+ +

예제

+ +

 toLowerCase()

+ +
console.log('ALPHABET'.toLowerCase()); // 'alphabet'
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
표준상태비고
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.5.4.16', 'String.prototype.toLowerCase')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.tolowercase', 'String.prototype.toLowerCase')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.tolowercase', 'String.prototype.toLowerCase')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.String.toLowerCase")}}

+ +

참조

+ + 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 +--- +
{{JSRef}} {{non-standard_header}}
+ +

The toSource() method returns a string representing the source code of the object.

+ +

문법

+ +
String.toSource()
+str.toSource()
+
+ +

리턴 값

+ +

호출한 객체의 소스코드가 string으로 보여집니다.

+ +

설명

+ +

toSource() 메소드는 다음 값을 리턴:

+ +

For the built-in {{jsxref("String")}} object, toSource() returns the following string indicating that the source code is not available:

+ +
function String() {
+    [native code]
+}
+
+ +

For instances of {{jsxref("String")}} or string literals, toSource() returns a string representing the source code.

+ +

This method is usually called internally by JavaScript and not explicitly in code.

+ +

Specifications

+ +

Not part of any standard. Implemented in JavaScript 1.3.

+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.String.toSource")}}

+ +

See also

+ + 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 +--- +
{{JSRef}}
+ +

toString()메소드는 지정된 객체를 나타내는 문자열을 반환합니다.

+ +
{{EmbedInteractiveExample ( "pages / js / string-tostring.html")}}
+ +

통사론

+ +
str.toString()
+ +

반환 값

+ +

호출 객체를 나타내는 문자열

+ +

기술

+ +

{{jsxref ( "String")}} 오브젝트 toString()는 {{jsxref ( "Object")}} 오브젝트 메소드를 대체 합니다. {{jsxref ( "Object.prototype.toString ()")}}을 상속하지 않습니다. {{jsxref ( "String")}} 오브젝트의 경우 toString()메소드는 오브젝트 의 문자열 표시를 리턴하며 {{jsxref ( "String.prototype.valueOf ()")}} 메소드와 동일합니다.

+ +

+ +

사용 toString()

+ +

다음 예제는 {{jsxref ( "String")}} 오브젝트의 문자열 값을 표시합니다.

+ +
var x = new String ( 'Hello world');
+
+console.log (x.toString ()); // 'Hello world'를 기록합니다.
+
+ +

명세서

+ + + + + + + + + + +
사양
{{SpecName ( 'ESDraft', '# sec-string.prototype.tostring', 'String.prototype.toString')}}}
+ +

브라우저 호환성

+ + + +

{{Compat ( "javascript.builtins.String.toString")}}

+ +

또한보십시오

+ + 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 +--- +
{{JSRef}}
+ +

toUpperCase() 메서드는 문자열을 대문자로 변환해 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/string-touppercase.html")}}
+ + + +

구문

+ +
str.toUpperCase()
+ +

반환 값

+ +

대문자로 변환한 새로운 문자열.

+ +

예외

+ +
+
{{jsxref("TypeError")}}
+
{{jsxref("Function.prototype.call()")}} 등을 사용해 {{jsxref("null")}}이나 {{jsxref("undefined")}}에서 호출 시.
+
+ +

설명

+ +

toUpperCase() 메서드는 문자열을 대문자로 변환한 값을 반환합니다. JavaScript의 문자열은 불변하므로 원본 문자열에는 영향을 주지 않습니다.

+ +

예제

+ +

기본 사용법

+ +
console.log('alphabet'.toUpperCase()); // 'ALPHABET'
+ +

문자열이 아닌 this의 문자열 변환

+ +

toUpperCase()this가 문자열이 아니고, undefinednull도 아니면 자동으로 문자열로 변환합니다.

+ +
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);
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태비고
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.5.4.18', 'String.prototype.toUpperCase')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.touppercase', 'String.prototype.toUpperCase')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.touppercase', 'String.prototype.toUpperCase')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.String.toUpperCase")}}

+ +

같이 보기

+ + 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 +--- +
{{JSRef}}
+ +

trim() 메서드는 문자열 양 끝의 공백을 제거합니다. 공백이란 모든 공백문자(space, tab, NBSP 등)와 모든 개행문자(LF, CR 등)를 의미합니다.

+ +
{{EmbedInteractiveExample("pages/js/string-trim.html")}}
+ + + +

구문

+ +
str.trim()
+ +

반환 값

+ +

양 끝에서 공백을 제거한 새로운 문자열.

+ +

설명

+ +

trim() 메서드는 양끝의 공백을 제거한 문자열을 반환합니다. trim()은 원본 문자열에는 영향을 주지 않습니다. 

+ +

예제

+ +

trim() 사용

+ +

아래의 예제는 소문자 문자열  'foo'를 표시합니다.

+ +
var orig = '   foo  ';
+console.log(orig.trim()); // 'foo'
+
+// 한 쪽의 공백만 제거하는 .trim() 예제
+
+var orig = 'foo    ';
+console.log(orig.trim()); // 'foo'
+
+ +

폴리필

+ +

다른 코드 전에 아래 코드를 실행하면 지원하지 않는 환경에서도  String.trim() 을 사용할 수 있습니다.

+ +
if (!String.prototype.trim) {
+  String.prototype.trim = function () {
+    return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
+  };
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
표준상태비고
{{SpecName('ES5.1', '#sec-15.5.4.20', 'String.prototype.trim')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.1.
{{SpecName('ES6', '#sec-string.prototype.trim', 'String.prototype.trim')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.trim', 'String.prototype.trim')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.String.trim")}}

+ +

참조

+ + 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 +--- +
{{JSRef}}
+ +

valueOf() 메서드는 {{jsxref("String")}} 객체의 원시값을 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/string-valueof.html")}}
+ +

구문

+ +
str.valueOf()
+ +

반환 값

+ +

지정된 {{jsxref("String")}} 객체의 원시 값을 나타내는 문자열.

+ +

설명

+ +

{{jsxref("String")}} 의 valueOf() 메서드는 {{jsxref("String")}} 객체의 원시 값을 문자열 데이터 타입으로 반환 합니다. 이 값은 {{jsxref("String.prototype.toString()")}}.과 동일합니다.

+ +

이 메서드는 보통 자바스크립트에 의해 내부적으로 호출되며, 코드에서 명시적으로 사용하지는 않습니다.

+ +

예제

+ +

  valueOf() 사용

+ +
var x = new String('Hello world');
+console.log(x.valueOf()); // 'Hello world' 가 보여집니다.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}초기 정의. JavaScript 1.1 에서 구현.
{{SpecName('ES5.1', '#sec-15.5.4.3', 'String.prototype.valueOf')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-string.prototype.valueof', 'String.prototype.valueOf')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-string.prototype.valueof', 'String.prototype.valueOf')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.String.valueOf")}}

+ +

같이 보기

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