언어/JavaScript
[ Javascript ] 문자열 다루기
Soso Dev
2025. 4. 12. 02:14
반응형
🌱 문자열을 다루는 방법 (JavaScript 전체 예제 포함)
JavaScript에서 문자열은 매우 자주 사용되는 데이터 타입이며, 이를 다루기 위한 다양한 메서드와 기술이 존재합니다. 문자열을 조작, 검색, 비교, 변환하는 방법들을 아래에 예제와 함께 정리하였습니다.
1. 문자열 생성
1. 리터럴 방식
const str = "Hello, world!";
console.log(str); // Hello, world!
2. String 생성자 사용
const strObj = new String("Hello");
console.log(strObj); // [String: 'Hello']
문자열 속성
const word = "hello";
console.log(word.length); // 5
2. 문자열 접근
1. 인덱스로 접근
const str = "hello";
console.log(str[1]); // "e"
2. charAt()
메서드
console.log(str.charAt(1)); // "e"
3. 문자열 결합
1. +
연산자
const msg = "Hello, " + "World!";
console.log(msg); // "Hello, World!"
2. concat()
메서드
const result = "Hello, ".concat("World!");
console.log(result); // "Hello, World!"
4. 문자열 검색
1. indexOf()
console.log("hello".indexOf("l")); // 2
2. lastIndexOf()
console.log("hello".lastIndexOf("l")); // 3
3. includes()
console.log("hello".includes("he")); // true
4. startsWith()
/ endsWith()
console.log("hello".startsWith("he")); // true
console.log("hello".endsWith("lo")); // true
5. 문자열 추출
1. slice(start, end)
console.log("hello".slice(1, 4)); // "ell"
2. substring(start, end)
console.log("hello".substring(1, 4)); // "ell"
3. substr(start, length)
(Deprecated)
console.log("hello".substr(1, 3)); // "ell"
6. 문자열 변경
1. replace(search, replacement)
console.log("hello world".replace("world", "JavaScript")); // "hello JavaScript"
2. replaceAll(search, replacement)
console.log("a-b-c".replaceAll("-", "/")); // "a/b/c"
7. 문자열 반복 및 패딩
1. repeat(count)
console.log("ha".repeat(3)); // "hahaha"
2. padStart(length, fillString)
/ padEnd()
console.log("5".padStart(3, "0")); // "005"
console.log("5".padEnd(3, "*")); // "5**"
8. 문자열 분할 및 결합
1. split(separator)
const fruits = "apple,banana,grape".split(",");
console.log(fruits); // ["apple", "banana", "grape"]
2. join(separator)
const joined = ["a", "b", "c"].join("-");
console.log(joined); // "a-b-c"
9. 문자열 대소문자 변경
console.log("Hello".toLowerCase()); // "hello"
console.log("hello".toUpperCase()); // "HELLO"
10. 문자열 공백 제거
1. trim()
console.log(" hello ".trim()); // "hello"
2. trimStart()
/ trimEnd()
console.log(" hello".trimStart()); // "hello"
console.log("hello ".trimEnd()); // "hello"
11. 템플릿 리터럴
const name = "철수";
const greeting = `안녕하세요, ${name}님`;
console.log(greeting); // "안녕하세요, 철수님"
12. 문자열 비교
console.log("apple" === "apple"); // true
console.log("apple".localeCompare("banana")); // -1
13. 기타 유용한 메서드
const text = "hello123";
console.log(text.match(/\d+/)); // ["123"]
console.log(text.search(/\d/)); // 5
console.log(text.toString()); // "hello123"
console.log(text.valueOf()); // "hello123"
이처럼 문자열은 다양한 메서드를 통해 가공할 수 있으며, 상황에 맞는 메서드를 선택하여 사용하면 효율적인 문자열 처리가 가능합니다.
반응형