본문 바로가기
Front-End/javascript

[Javascript 기초] 문자열 내장함수

by 김기. 2023. 5. 17.

문자열 내장함수

1. String.length

2. String.indexOf()

3. String.slice()

4. String.substr()

5. String.replace()

6. String.split()


1. String.length

String.length는 문자열의 길이를 반환해 주는 속성입니다. (메소드 x)

const txt = "Hello World";
console.log(txt.length); // 11

 

2. String.indexOf()

String.indexOf()는 찾고자 하는 문자열의 위치를 반환해 줍니다.

주로 해당 문자가 포함돼 있는 지 탐색할 때 사용합니다. (포함돼 있지 않으면 -1 출력)

const txt = "Hello World";
console.log(txt.indexOf("Wo")); // 6
console.log(txt.indexOf("apple")); // -1

 

3. String.slice()

문자열에서 특정 부분을 추출해서 새로운 문자열로 반환합니다.

첫 번째 인수로는 문자열 추출 시작 지점, 두 번째 인수로는 추출 마지막 지점을 넣어줍니다.

const txt = "Hello Wolrd";
const txt2 = txt.slice(0, 5);

console.log(txt2); //Hello

 

4. String.substr()

문자열에서 특정 위치부터 특정 문자 수 만큼 반환합니다. 즉, 특정 부분을 잘라냅니다.

첫 번째 인수로는 문자열 추출 시작 지점, 두 번째 인수로는 추출하려는 길이를 넣어줍니다.

const txt = "Hello Wolrd";
const txt2 = txt.substr(6, 3);

console.log(txt2); // Wol

이 메소드는 특정 문자수를 초과하면 "..."을 붙이고 남은 문자를 지우는 방법으로 응용할 수 있습니다.

const origin = "동해물과 백두산이 마르고 닳도록 하느님이 보우하사 우리나라 만세";
let result = '';

if(origin.length > 15){
  result = origin.substr(0, 15)+"...";
}else{
  result = origin;
}

console.log(result); // 동해물과 백두산이 마르고 닳...
// 삼항 연산자를 사용한 구문
// ?앞의 조건식이 참이면 ?뒤의 코드가 실행되고, 거짓이면 :뒤의 코드가 실행

const origin = "동해물과 백두산이 마르고 닳도록 하느님이 보우하사 우리나라 만세";
let result = '';

(origin.length > 15) ? result = origin.substr(0, 15)+"..." : result = origin;

console.log(result); // 동해물과 백두산이 마르고 닳...

 

5. String.replace()

문자열에서 특정 문자값을 교체된 문자값으로 반환합니다.

const introduce = "우리 BRAND는 수준 높은 서비스를 자랑하고 BRAND의 가치를 높이기 위해서 최선을 다합니다. 앞으로도 BRAND 많은 관심 부탁드립니다.";

const intro2 = introduce.replace(/BRAND/ig, "brand");

console.log(intro2); // 우리 brand는 수준 높은 서비스를 자랑하고 brand의 가치를 높이기 위해서 최선을 다합니다. 앞으로도 brand 많은 관심 부탁드립니다.

 

6. String.split()

문자열을 지정한 구분자를 이용해 여러 배열로 나눕니다.

const fruits = "apple, grape, muskmelon";
const arr = fruits.split(",")

console.log(arr); // ['apple', ' grape', ' muskmelon']

댓글