第13講

문자열 다루기

3 閲覧 1

자바스크립트 문자열의 불변성과 주요 메서드를 익힌다. 템플릿 리터럴 고급 활용, 정규표현식 기초, 그리고 문자열 파싱과 포맷팅 실무 패턴을 배운다.

문자열 — 불변한 텍스트 시퀀스

자바스크립트 문자열은 불변(immutable)입니다. 문자열 메서드는 원본을 변경하지 않고 항상 새 문자열을 반환합니다. 내부적으로 UTF-16으로 인코딩되며, 이모지처럼 서로게이트 쌍을 사용하는 문자는 length가 2로 계산됩니다.

문자열 생성과 기본 프로퍼티

const str1 = "큰따옴표";
const str2 = "작은따옴표";
const str3 = `템플릿 리터럴`;

str1.length    // 5 (글자 수)
str1[0]        // "큰"
str1.at(-1)    // "표" (ES2022, 음수 인덱스)

// 이모지 length 주의
"👍".length    // 2 (서로게이트 쌍)
[..."👍"].length // 1 (스프레드로 올바른 길이)

검색 메서드

const text = "Hello, World! Hello, JavaScript!";

text.indexOf("Hello")       // 0 (첫 번째 위치)
text.lastIndexOf("Hello")   // 14
text.indexOf("Python")      // -1 (없으면 -1)
text.includes("World")      // true
text.startsWith("Hello")    // true
text.endsWith("!")          // true
text.startsWith("World", 7) // true (7번 인덱스부터 시작)

추출 메서드

const str = "Hello, World!";

// slice(start, end) — 음수 인덱스 지원, 권장
str.slice(0, 5)    // "Hello"
str.slice(7)       // "World!"
str.slice(-6)      // "orld!" 잠깐 — "orld!" → 실제로 "World!"에서 slice(-6) = "orld!"

str.slice(7, 12)   // "World"
str.slice(-6, -1)  // "World"

// substring(start, end) — 음수는 0으로 처리
str.substring(7, 12) // "World"

// charAt — 인덱스 위치 문자
str.charAt(0)        // "H"
str[0]               // "H" (동일)

변환 메서드

const str = "  Hello, World!  ";

// 대소문자
"hello".toUpperCase()  // "HELLO"
"HELLO".toLowerCase()  // "hello"

// 공백 제거
str.trim()             // "Hello, World!"
str.trimStart()        // "Hello, World!  "
str.trimEnd()          // "  Hello, World!"

// 교체
"a-b-c".replace("-", "_")     // "a_b-c" (첫 번째만)
"a-b-c".replaceAll("-", "_")  // "a_b_c" (모두)

// 분할
"a,b,c".split(",")            // ["a", "b", "c"]
"Hello".split("")             // ["H", "e", "l", "l", "o"]
"Hello World".split(" ")      // ["Hello", "World"]
"a,,b".split(",")             // ["a", "", "b"]

// 연결
"Hello".concat(" ", "World!")  // "Hello World!"
["Hello", "World"].join(" ")   // "Hello World" (배열 → 문자열)

// 채우기
"5".padStart(3, "0")  // "005" (왼쪽 채우기)
"5".padEnd(3, "0")    // "500" (오른쪽 채우기)

// 반복
"ha".repeat(3)        // "hahaha"

템플릿 리터럴 고급 활용

// 다중 줄
const multiLine = `첫 번째 줄
두 번째 줄
세 번째 줄`;

// 표현식 포함
const price = 29900;
const tax = 0.1;
const receipt = `상품 가격: ${price.toLocaleString()}원
세금: ${(price * tax).toLocaleString()}원
합계: ${(price * (1 + tax)).toLocaleString()}원`;

// 조건 표현식
const score = 85;
const message = `당신의 점수: ${score}점 — ${score >= 90 ? "우수" : score >= 70 ? "보통" : "미흡"}`;

// 함수 호출
const name = "  kim  ";
console.log(`이름: ${name.trim().toUpperCase()}`); // "이름: KIM"

// 태그드 템플릿 (고급)
function highlight(strings, ...values) {
  return strings.reduce((result, str, i) => {
    return result + str + (values[i] ? `${values[i]}` : "");
  }, "");
}
const user = "Kim";
highlight`안녕하세요, ${user}님! 점수는 ${score}점입니다.`;
// "안녕하세요, Kim님! 점수는 85점입니다."

정규표현식 기초

// 리터럴 방식과 생성자 방식
const regex1 = /hello/i;        // 리터럴 (i: 대소문자 무시)
const regex2 = new RegExp("hello", "i"); // 생성자

// 주요 메서드
"Hello World".match(/\w+/g);       // ["Hello", "World"]
"Hello World".search(/World/);     // 6 (인덱스)
"Hello World".replace(/World/, "JS"); // "Hello JS"
/^\d+$/.test("12345");             // true (숫자만 있는지)

// 자주 쓰는 패턴
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
emailRegex.test("test@example.com"); // true
emailRegex.test("invalid-email");    // false

const phoneRegex = /^010-?\d{4}-?\d{4}$/;
phoneRegex.test("010-1234-5678");    // true
phoneRegex.test("01012345678");      // true

숫자 → 문자열 포맷팅

const price = 1234567.89;

// 천 단위 구분
price.toLocaleString("ko-KR");        // "1,234,567.89"
price.toLocaleString("ko-KR", {
  style: "currency",
  currency: "KRW"
});
// "₩1,234,568"

// 소수점 자리수
(3.14159).toFixed(2)    // "3.14" (문자열 반환!)
(3.14159).toPrecision(4) // "3.142" (전체 자릿수)

// 진법 변환
(255).toString(16)  // "ff" (16진수)
(255).toString(2)   // "11111111" (2진수)
parseInt("ff", 16)  // 255
parseInt("11111111", 2) // 255

관련 검색어  ·  자바스크립트 문자열 메서드, 템플릿 리터럴 활용, 정규표현식 기초, split join, 문자열 포맷팅, toLocaleString

채용정보
공지사항
인사이트
MY