[mjt] 자주 사용되는 문자열 메서드에 대해 알아보자
자주 사용되는 문자열 메서드에 대해 알아보자
자바스크립트에서 글자 하나만 저장할 수 있는 별도의 자료형이 없다. 텍스트 형식의 데이터는 길이에 상관없이 문자열 형태로 저장되며, 문자열과 관련된 메서드에 대해 알아보자
charAt()
주어진 인덱스에 해당하는 문자를 반환한다.
const str = "Hello, World!";
console.log(str.charAt(0)); // H
includes()
문자열에 특정 문자열이 포함되어 있는지 확인한다.
const str = "Hello, World!";
console.log(str.includes("World")); // true
indexOf()
특정 문자열이 처음 나타나는 인덱스를 반환한다. 없으면 -1
을 반환한다.
const str = "Hello, World!";
console.log(str.indexOf("o")); // 4
slice()
문자열의 일부분을 추출하여 새로운 문자열을 반환한다.
const str = "Hello, World!";
console.log(str.slice(0, 5)); // Hello
replace()
문자열의 특정 부분을 다른 문자열로 대체한다.
const str = "Hello, World!";
console.log(str.replace("World", "JavaScript")); // Hello, JavaScript!
split()
문자열을 주어진 구분자를 기준으로 나누어 배열로 반환한다.
const str = "apple, banana, cherry";
console.log(str.split(", "));
["apple", "banana", "cherry"];
toUpperCase(), toLowerCase()
문자열을 대문자 또는 소무자로 변환한다.
const str = "Hello, World!";
console.log(str.toUpperCase()); // HELLO, WORLD!
console.log(str.toLowerCase()); // hello, world!
trim()
문자열의 양쪽 끝에 있는 공백을 제거한다.
const str = " Hello, World! ";
console.log(str.trim()); // "Hello, World!"
substring()
문자열의 일부분을 추출한다. slice()
와 유사하지만 음수 인덱스를 지원하지 않는다.
const str = "Hello, World!";
console.log(str.substring(0, 5)); // Hello
:ten: concat()
두 개 이상의 문자열을 연결한다.
const str1 = "Hello";
const str2 = "World";
console.log(str1.concat(", ", str2, "!")); // Hello, World!
:eleven: startWith(), endWith()
문자열이 특정 문자로 시작하거나 끝나는지 확인한다.
const str = "Hello, World!";
console.log(str.startsWith("Hello")); // true
console.log(str.endsWith("!")); // true