1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
|
---
title: String
slug: Web/JavaScript/Reference/Global_Objects/String
tags:
- ECMAScript 2015
- JavaScript
- Reference
- String
translation_of: Web/JavaScript/Reference/Global_Objects/String
---
<div>{{JSRef}}</div>
<p><strong><code>String</code></strong> 전역 객체는 문자열(문자의 나열)의 생성자입니다.</p>
<h2 id="Syntax" name="Syntax">구문</h2>
<p>문자열 리터럴은 다음과 같은 형식을 사용합니다.</p>
<pre class="syntaxbox">'string text'
"string text"
"中文 español Deutsch English देवनागरी العربية português বাংলা русский 日本語 norsk bokmål ਪੰਜਾਬੀ 한국어 தமிழ் עברית"</pre>
<p>문자열은 <code>String</code> 전역 객체를 직접 사용하여 생성할 수 있습니다.</p>
<pre class="syntaxbox">String(<em>thing</em>)</pre>
<h3 id="매개변수">매개변수</h3>
<dl>
<dt><code>thing</code></dt>
<dd>문자열로 변환할 아무 값.</dd>
<dt>
<h3 id="템플릿_리터럴">템플릿 리터럴</h3>
</dt>
</dl>
<p>ECMAScript 2015 이후, 문자열 리터럴은 소위 <a href="/ko/docs/Web/JavaScript/Reference/Template_literals">템플릿 리터럴</a>이 될 수 있습니다.</p>
<pre class="language-html"><code class="language-html">`hello world` `hello! world!` `hello ${who}` tag `<span class="tag token"><span class="tag token"><span class="punctuation token"><</span>a</span><span class="punctuation token">></span></span>${who}<span class="tag token"><span class="tag token"><span class="punctuation token"></</span>a</span><span class="punctuation token">></span></span>`</code></pre>
<h3 id="이스케이프_표현">이스케이프 표현</h3>
<p>일반적인 출력 문자 외의 특수 문자는 이스케이프 표현을 사용해 적을 수 있습니다.</p>
<table class="standard-table">
<thead>
<tr>
<th scope="col">코드</th>
<th scope="col">출력</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>\XXX</code></td>
<td>8진수 Latin-1 문자</td>
</tr>
<tr>
<td><code>\'</code></td>
<td>작은따옴표</td>
</tr>
<tr>
<td><code>\"</code></td>
<td>큰따옴표</td>
</tr>
<tr>
<td><code>\\</code></td>
<td>역슬래시</td>
</tr>
<tr>
<td><code>\n</code></td>
<td>개행</td>
</tr>
<tr>
<td><code>\r</code></td>
<td>캐리지 리턴</td>
</tr>
<tr>
<td><code>\v</code></td>
<td>세로 탭</td>
</tr>
<tr>
<td><code>\t</code></td>
<td>탭</td>
</tr>
<tr>
<td><code>\b</code></td>
<td>백 스페이스</td>
</tr>
<tr>
<td><code>\f</code></td>
<td>폼 피드</td>
</tr>
<tr>
<td><code>\uXXXX</code></td>
<td>유니코드 코드포인트</td>
</tr>
<tr>
<td><code>\u{X}</code> ... <code>\u{XXXXXX}</code></td>
<td>유니코드 코드포인트 {{experimental_inline}}</td>
</tr>
<tr>
<td><code>\xXX</code></td>
<td>Latin-1 문자</td>
</tr>
</tbody>
</table>
<div class="note">
<p>일부 다른 프로그래밍 언어와 달리, JavaScript는 작은따옴표와 큰따옴표 문자열을 구분하지 않습니다. 따라서 위의 이스케이프 문자는 작은따옴표나 큰따옴표에서 상관 없이 작동합니다.</p>
</div>
<h3 id="긴_문자열_리터럴">긴 문자열 리터럴</h3>
<p>작성한 코드가 매우 긴 문자열을 포함해야 하는 경우, 끝 없이 뻗어나가는 한 줄이나 편집기의 재량에 따라 자동으로 줄을 넘기는 대신 직접 여러 줄로 나누되 내용에는 영향을 주지 않고 싶을 때가 있을겁니다. 이런 상황에는 두 가지 방법을 사용할 수 있습니다.</p>
<p>우선 다음과 같이 <a href="/ko/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#%EB%8D%94%ED%95%98%EA%B8%B0_()">+</a> 연산자를 사용할 수 있습니다.</p>
<pre class="brush: js"><code>let longString = "여러 줄에 걸쳐 작성해야 할 정도로 " +
"긴 문자열인데 왜 한 줄에 다 적으면 안되냐면 " +
"코드를 읽기 힘들어지니까요.";</code></pre>
<p>아니면 역슬래시 문자("\")를 각 줄의 맨 끝에 붙여 문자열이 이어진다는걸 표시할 수도 있습니다. 역슬래시 다음에 공백을 포함한 어떤 문자라도 붙으면 제대로 작동하지 않으므로 주의해야 합니다.</p>
<pre class="brush: js"><code>let longString = "여러 줄에 걸쳐 작성해야 할 정도로 \
긴 문자열인데 왜 한 줄에 다 적으면 안되냐면 \
코드를 읽기 힘들어지니까요.";</code></pre>
<p>두 예시 모두 동일한 문자열을 생성합니다.</p>
<h2 id="Description" name="Description">설명</h2>
<p>문자열은 텍스트 형태로 표현될 수있는 데이터를 보관하는 데 유용합니다. 문자열에서 가장 많이 사용되는 작업들은 문자열의 길이를 확인하는 ({{jsxref("String.length", "length")}}), 문자열을 생성하고 연결하는 <a href="/ko/docs/Web/JavaScript/Reference/Operators/String_Operators" title="JavaScript/Reference/Operators/String_Operators">+ 와 += 문자열 연산자</a>, 서브문자열(substring)이 있는지 확인하고, 있으면 위치를 확인하는 {{jsxref("String.prototype.indexOf()", "indexOf()")}} 메서드, 서브문자열(substring)을 추출해내는 {{jsxref("String.prototype.substring()", "substring()")}} 메서드가 있습니다.</p>
<h3 id="문자_접근">문자 접근</h3>
<p>문자열에서 개개의 문자에 접근할 수 있는 방법은 두가지가 있습니다. 첫번째는 {{jsxref("String.prototype.charAt()", "charAt()")}} 메서드를 이용하는 것입니다:</p>
<pre class="brush: js">return 'cat'.charAt(1); // returns "a"
</pre>
<p>다른 방법(ECMAScript 5에서 소개하고 있는)은 문자열을 배열과 같은 오브젝트로 취급하여, 문자에 해당하는 숫자 인덱스를 사용하는 방법입니다 :</p>
<pre class="brush: js">return 'cat'[1]; // returns "a"
</pre>
<p>브라켓([ ]) 표기법을 사용하여 문자에 접근하는 경우 , 이러한 프로퍼티들에 새로운 값을 할당하거나 삭제할 수는 없습니다. 포함되어 있는 프로퍼티들은 작성할 수도, 수정할 수도 없습니다. (더 자세한 정보는 {{jsxref("Object.defineProperty()")}}를 참고 바랍니다 .)</p>
<h3 id="Comparing_strings" name="Comparing_strings">문자열 비교</h3>
<p>C 개발자는 문자열 비교를 위하여 <code><span style="font-family: courier new,andale mono,monospace;">strcmp()</span></code> 함수를 사용합니다. JavaScript에서는 단지 <a href="/ko/docs/Web/JavaScript/Reference/Operators/Comparison_Operators" style="line-height: inherit;" title="JavaScript/Reference/Operators/Comparison_Operators">less-than와 greater-than 연산자</a>만을 사용하여 문자열을 비교할 수 있습니다<span style="line-height: inherit;"> </span><span style="line-height: inherit;">:</span></p>
<pre class="brush: js">var a = "a";
var b = "b";
if (a < b) { // true
console.log(a + " is less than " + b);
} else if (a > b) {
console.log(a + " is greater than " + b);
} else {
console.log(a + " and " + b + " are equal.");
}
</pre>
<p>비슷한 결과를 얻을 수 있는 방법으로 <span style="font-family: courier new,andale mono,monospace;">String</span> 인스턴스에서 상속된 {{jsxref("String.prototype.localeCompare()", "localeCompare()")}} 메서드를 사용할 수 있습니다.</p>
<h3 id="문자열_원형과_String_객체의_차이">문자열 원형과 <code>String</code> 객체의 차이</h3>
<div>JavaScript는 <code>String</code> 오브젝트와 원형의 문자열을 다르게 취급한다는 것에 주의해야 합니다. ({{jsxref("Boolean")}}과 <a href="/ko/docs/Web/JavaScript/Reference/Global_Objects" title="JavaScript/Reference/Global_Objects/">숫자</a>의 true도 마찬가지입니다.)</div>
<div> </div>
<p>문자열 리터럴(작은 따옴표 또는 큰 따옴표로 생성되는)과 생성자 없이(즉. {{jsxref("Operators/new", "new")}} 키워드를 사용하지 않고) <code>String</code>을 호출하여 반환된 문자열은 원형 문자열(primitive strings)입니다. JavaScript는 자동적으로 원형을 <code>String</code> 오브젝트로 변환하기 때문에, <code>String</code> 오브젝트 메서드를 사용하여 원형문자열을 생성할 수 있습니다. 문맥 안의 메서드에서 프로퍼티 조회 또는 원형의 문자열 호출이 발생하면, JavaScript는 자동으로 문자열 원형을 감싸고 프로퍼티 조회를 수행 하거나 메서드를 호출합니다.</p>
<pre class="brush: js">var s_prim = "foo";
var s_obj = new String(s_prim);
console.log(typeof s_prim); // Logs "string"
console.log(typeof s_obj); // Logs "object"
</pre>
<p>문자열 원형과 <code>String</code> 오브젝트는 {{jsxref("Global_Objects/eval", "eval()")}}을 사용할 때 다른 결과를 제공합니다. <code>eval</code>에 전달되는 문자열 원형들은 소스 코드 취급을 받습니다; <code>String</code> 오브젝트들은 다른 모든 오브젝트들과 마찬가지로 취급하며, 오브젝트를 반환합니다. 예를 들면:</p>
<pre class="brush: js">var s1 = '2 + 2'; // creates a string primitive
var s2 = new String('2 + 2'); // creates a String object
console.log(eval(s1)); // returns the number 4
console.log(eval(s2)); // returns the string "2 + 2"
</pre>
<p>이러한 이유로, 비록 코드 상에서 원형 문자열을 사용하는 대신에 <code>String</code> 오브젝트를 사용하게 되면 코드가 손상될 수 있지만, 일반적인 개발자는 차이를 걱정할 필요는 없습니다.</p>
<p><code>String</code><span style="line-height: inherit;"> 오프젝트는 언제든지 </span>{{jsxref("String.prototype.valueOf()", "valueOf()")}} <span style="line-height: inherit;"> 메서드로 원형에 대응하도록 전환할 수 있습니다.</span></p>
<pre class="brush: js">console.log(eval(s2.valueOf())); // returns the number 4
</pre>
<h2 id="Properties" name="Properties">속성</h2>
<dl>
<dt>{{jsxref("String.prototype")}}</dt>
<dd>String 오브젝트는 프로퍼티의 추가가 가능합니다.</dd>
</dl>
<h2 id="Methods" name="Methods">메서드</h2>
<dl>
<dt>{{jsxref("String.fromCharCode()")}}</dt>
<dd>지정된 유니코 값의 순서를 이용하여 만든 문자열을 반환합니다.</dd>
<dt>{{jsxref("String.fromCodePoint()")}} {{experimental_inline}}</dt>
<dd>지정된 코드 포인트 순서를 이용하여 만든 문자열을 반환합니다.</dd>
<dt>{{jsxref("String.raw()")}} {{experimental_inline}}</dt>
<dd>원형 템플릿 문자열(raw template string)에서 생성된 문자열을 반환합니다.</dd>
</dl>
<h2 id="String_generic_메서드"><code>String</code> generic 메서드</h2>
<div class="warning">
<p><strong><code>String</code> generic들은 비표준으로, 가까운 미래에 사라질 것입니다.</strong> 아래에서 제공하고 있는 방식을 사용하지 않으면, 브라우저들간의 호환성은 기대하기 어렵습니다. </p>
</div>
<p><code>String</code><span style="line-height: inherit;"> 인스턴스 메서드는 JavScript 1.6으로 Firefox에서(ECMAScript 표준에 속하지는 않지만) 어떤 오브젝트라도 String 메서드에 적용하여 String 오브젝트에서 사용가능합니다:</span></p>
<pre class="brush: js">var num = 15;
console.log(String.replace(num, /5/, '2'));
</pre>
<p class="brush: js">{{jsxref("Global_Objects/Array", "Generics", "#Array_generic_methods", 1)}}은<span style="line-height: inherit;"> </span>{{jsxref("Global_Objects/Array", "Array")}}<span style="line-height: inherit;"> 메서드에도 사용 가능합니다.</span></p>
<h2 id="String_instances" name="String_instances"><code>String</code> 인스턴스</h2>
<h3 id="속성">속성</h3>
<p>{{ page('ko/docs/JavaScript/Reference/Global_Objects/String/prototype', 'Properties') }}</p>
<h3 id="메서드">메서드</h3>
<h4 id="HTML과_관계없는_메서드">HTML과 관계없는 메서드</h4>
<p>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Methods_unrelated_to_HTML')}}</p>
<h4 id="HTML_wrapper_methods">HTML wrapper methods</h4>
<p>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'HTML_wrapper_methods')}}</p>
<h2 id="예제">예제</h2>
<h3 id="문자열_변환">문자열 변환</h3>
<p>비록 일반적으로 toString() 함수를 많이 사용하고 있지만, {{jsxref("String.prototype.toString()", "toString()")}}의 "안전한" 대안으로 String을 사용할 수 있습니다. String은 {{jsxref("Global_Objects/null", "null")}}과 {{jsxref("Global_Objects/undefined", "undefined")}}에 대해서도 잘 동작합니다. 예를 들면: </p>
<pre class="brush: js">var outputStrings = [];
for (var i = 0, n = inputValues.length; i < n; ++i) {
outputStrings.push(String(inputValues[i]));
}
</pre>
<h2 id="Browser_Compatibility" name="Browser_Compatibility">명세</h2>
<table class="standard-table">
<tbody>
<tr>
<th scope="col">Specification</th>
<th scope="col">Status</th>
<th scope="col">Comment</th>
</tr>
<tr>
<td>{{SpecName('ES1')}}</td>
<td>{{Spec2('ES1')}}</td>
<td>Initial definition.</td>
</tr>
<tr>
<td>{{SpecName('ES5.1', '#sec-15.5', 'String')}}</td>
<td>{{Spec2('ES5.1')}}</td>
<td> </td>
</tr>
<tr>
<td>{{SpecName('ES6', '#sec-string-objects', 'String')}}</td>
<td>{{Spec2('ES6')}}</td>
<td> </td>
</tr>
<tr>
<td>{{SpecName('ESDraft', '#sec-string-objects', 'String')}}</td>
<td>{{Spec2('ESDraft')}}</td>
<td> </td>
</tr>
</tbody>
</table>
<h2 id="Browser_Compatibility" name="Browser_Compatibility">브라우저 호환성</h2>
<p>{{Compat("javascript.builtins.String",2)}}</p>
<h2 id="같이_보기">같이 보기</h2>
<ul>
<li>{{domxref("DOMString")}}</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/DOMString/Binary">Binary strings</a></li>
</ul>
|