[javascript] 문자열 다루기

자바스크립트는 문자열을 다루는 다양한 함수와 메서드를 제공합니다. 이 블로그 포스트에서는 일반적으로 사용되는 문자열 다루기 관련 기능과 사용 예제를 살펴보겠습니다.

1. 문자열 길이 확인하기

문자열의 길이를 확인하려면 length 속성을 사용합니다. 다음은 예제 코드입니다.

const str = "Hello, World!";
const length = str.length;
console.log(length); // 13

2. 문자열 자르기

slice, substring, substr 등의 메서드를 사용하여 문자열을 자를 수 있습니다. 각 메서드의 동작 방식은 조금씩 다르므로 상황에 맞게 선택하여 사용해야 합니다.

const str = "Hello, World!";
const slicedStr = str.slice(0, 5);
console.log(slicedStr); // Hello

const subsStr = str.substring(7, 12);
console.log(subsStr); // World

const substrStr = str.substr(7, 5);
console.log(substrStr); // World

3. 문자열 분리 및 합치기

split 메서드를 사용하여 문자열을 특정 구분자를 기준으로 분리할 수 있습니다. join 메서드를 사용하면 분리된 문자열을 다시 합칠 수 있습니다.

const str = "apple,banana,grape";
const arr = str.split(",");
console.log(arr); // ["apple", "banana", "grape"]

const newStr = arr.join("-");
console.log(newStr); // apple-banana-grape

4. 문자열 검색

indexOf, lastIndexOf, includes, startsWith, endsWith 등의 메서드를 사용하여 문자열 내에서 특정 문자열을 검색할 수 있습니다.

const str = "Hello, World!";
console.log(str.indexOf("o")); // 4
console.log(str.includes("World")); // true
console.log(str.startsWith("Hello")); // true
console.log(str.endsWith("!")); // true

5. 문자열 변경

replace 메서드를 사용하여 문자열 내의 특정 부분을 다른 문자열로 변경할 수 있습니다.

const str = "Hello, World!";
const newStr = str.replace("World", "Universe");
console.log(newStr); // Hello, Universe!

6. 대소문자 변환

toUpperCase, toLowerCase 메서드를 사용하여 문자열의 대소문자를 변환할 수 있습니다.

const str = "Hello, World!";
console.log(str.toUpperCase()); // HELLO, WORLD!
console.log(str.toLowerCase()); // hello, world!

위에서 살펴본 기능들은 자바스크립트에서 문자열을 효과적으로 다룰 수 있는 기본적인 방법들입니다. 문자열 처리는 프로그래밍에서 매우 중요하므로, 이러한 기능들을 잘 숙지하는 것이 중요합니다.

이상으로 문자열 다루기에 관한 내용을 정리해보았습니다.

관련 참고 자료