[Javascript] String
JS String, JavaScript 문자열, template literal
정의
JavaScript 의 string 은 UTF-16 코드 유닛의 불변 시퀀스. 작은따옴표, 큰따옴표, 백틱 (template literal) 으로 작성.
const a = 'single';
const b = "double";
const c = `template`;
typeof a // 'string'
Template Literal
const name = 'Alice';
const age = 30;
const s = `My name is ${name} and I am ${age}`;
// 멀티라인
const multi = `line 1
line 2
line 3`;
// 표현식
const result = `2 + 2 = ${2 + 2}`;
tagged template
function tag(strings, ...values) {
return strings.reduce((acc, str, i) =>
acc + str + (values[i] ?? ''), '');
}
const x = tag`Hello, ${name}!`;
SQL, GraphQL, HTML 라이브러리에서 자주 사용 (예: sql 태그 함수로 안전한 쿼리 빌더).
자주 쓰는 메서드
| 메서드 | 의미 |
|---|---|
.length | 글자 수 (UTF-16 단위) |
.charAt(i), s[i] | i 번째 글자 |
.indexOf(s), .lastIndexOf(s) | 위치 |
.includes(s) | 포함 여부 |
.startsWith(s), .endsWith(s) | 시작/끝 검사 |
.slice(start, end), .substring(start, end) | 부분 |
.split(sep) | 분할 |
.replace(pat, repl), .replaceAll(pat, repl) | 치환 |
.match(regex), .matchAll(regex) | 정규식 매칭 |
.search(regex) | 정규식 위치 |
.toLowerCase(), .toUpperCase() | 대소문자 |
.trim(), .trimStart(), .trimEnd() | 공백 제거 |
.padStart(n, ch), .padEnd(n, ch) | 패딩 |
.repeat(n) | 반복 |
.normalize('NFC') | 유니코드 정규화 |
.at(i) | i 번째 (음수 인덱스) |
'Hello'.length // 5
'Hello'[0] // 'H'
'Hello'.slice(1, 4) // 'ell'
'Hello'.split('l') // ['He', '', 'o']
'a-b-c'.split('-') // ['a', 'b', 'c']
'aaa'.replace('a', 'b') // 'baa' (첫 번째만)
'aaa'.replaceAll('a', 'b') // 'bbb'
' hi '.trim() // 'hi'
'5'.padStart(3, '0') // '005'
'-'.repeat(5) // '-----'
immutable
const s = 'hello';
s[0] = 'H'; // 무시 (sloppy) 또는 TypeError (strict)
console.log(s); // 'hello'
s = s.toUpperCase(); // 새 문자열 할당 (s 가 const 면 ❌)
let t = s.toUpperCase(); // ✓
모든 변환 메서드는 새 문자열 반환.
유니코드 함정
'😀'.length // 2 (surrogate pair)
'😀'.charAt(0) // '\uD83D' (의미 없음)
[...'😀'] // ['😀'] (iterator 가 코드 포인트 단위)
'😀'.codePointAt(0) // 128512 (정확한 코드 포인트)
String.fromCodePoint(128512) // '😀'
이모지, 한자 일부, 글자 결합 (다이크리틱) 등이 1 글자가 아닐 수 있다. 정확한 grapheme 카운트는 Intl.Segmenter 또는 외부 라이브러리.
String vs string
'hello' // primitive
new String('hello') // String 객체 (사용 X)
typeof 'hello' // 'string'
typeof new String('hi') // 'object'
'hello'.length // 5 (자동 boxing)
primitive 가 표준. new String 은 사용하지 말 것.
비교
'apple' < 'banana' // true (사전순, char code)
'B' < 'a' // true ('B' = 66, 'a' = 97)
'한' < '글' // 유니코드 코드 포인트 비교
'한'.localeCompare('글', 'ko-KR') // 로케일 기반 (음수/0/양수)
한글, 다른 언어 정렬은 localeCompare 또는 Intl.Collator 권장.
함정
1. 숫자 + 문자열
'5' + 3 // '53' (string concatenation)
'5' - 3 // 2 (number)
'5' * 3 // 15
+'5' // 5 (string → number)
2. == 의 형변환
'5' == 5 // true (강제 변환)
'5' === 5 // false
항상 === 권장.
3. 정규식 replace 의 special $
'abc'.replace('b', '$&') // 'abbc' ($& = matched)
'abc'.replaceAll('b', '$$') // 'a$c' ($$ = literal $)
literal $ 를 넣으려면 escape.
💬 댓글