[JavaScript] String: 메서드, 정규식, 템플릿 리터럴
JS String str pattern, JS String, String methods, template literal, 정규식
정의
JavaScript 문자열은 불변 (immutable) UTF-16 시퀀스. 메서드는 새 문자열을 반환.
자주 쓰는 메서드
const s = 'Hello, World!';
s.length; // 13
s.indexOf('W'); // 7
s.slice(7, 12); // 'World'
s.substring(7); // 'World!'
s.replace('World', 'JS'); // 'Hello, JS!'
s.replaceAll('l', 'L'); // 'HeLLo, WorLd!'
s.split(', '); // ['Hello', 'World!']
s.toLowerCase(); // 'hello, world!'
s.trim(); // 공백 제거
s.padStart(20, '*'); // '*******Hello, World!'
s.at(-1); // '!'
s.includes('World'); // true
정규식
// literal
const re = /hello/i;
'Hello world'.match(re); // ['Hello']
// group + replace
'2026-06-29'.replace(/(\d+)-(\d+)-(\d+)/, '$3/$2/$1'); // '29/06/2026'
// exec 반복
const re2 = /\w+/g;
let m;
while ((m = re2.exec(s)) !== null) console.log(m[0]);
템플릿 리터럴
const name = 'A';
const greeting = `Hello, ${name}!`;
// 여러 줄
const multi = `line 1
line 2`;
// 태그드
function html(strings, ...values) {
return strings.reduce((r, s, i) => r + s + (values[i] ?? ''), '');
}
html`<p>${name}</p>`;
참고
- 관련 Regex
- 관련 UTF-16 인코딩
💬 댓글