🌎 Web/JavaScript

[JavaScript] 자바스크립트 문자열 메서드 총정리

오늘 ONEUL 2022. 4. 6. 02:16

문자열 길이

  • length - 문자열의 길이 반환
let txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let length = txt.length; // 26

 

 

 

 

문자열 부분 추출

문자열의 일부를 추출하고 새 문자열로 반환

  • slice(startIndex, endIndex) - 매개변수로 시작 위치와 끝 위치(포함 X)를 사용한다. 매개변수가 음수이면 문자열의 끝에서 시작한다.
  • substring(startIndex, endIndex) - slice와 비슷하나, 매개변수로 음수는 사용할 수 없다.
  • substr(startIndex, length) - slice와 비슷하나, 두 번째 매개변수는 추출할 부분의 길이를 지정한다.
let str = "Apple, Banana, Kiwi";
let startIndex = 0;
let endIndex = 6; // endIndex값은 미포함
console.log(str.slice(startIndex, endIndex)); // Apple,

// 파라미터가 1개일 때는 문자값 끝까지
console.log(str.slice(7)); // Banana, Kiwi
console.log(str.slice(7, str.length)); // Banana, Kiwi

// 파라미터에 음수를 사용하면 문자값 뒤에서 출발
console.log(str.slice(-1)); // i

// count는 문자 선택 갯수
let count = 5;
console.log(str.substr(startIndex, count)); // Apple

// 파라미터가 1개일 때는 지정 인덱스로부터 문자값 끝까지
console.log(str.substring(13)); // , Kiwi
console.log(str.substr(13, str.length-13)); // , Kiwi

 

 

 

 

문자열 대체

  • replace(oldStr, newStr) - 지정된 값을 다른 값으로 바꾸고 새 문자열로 반환. 첫 일치 항목만 대체하고, 대소문자를 구분한다. 정규식을 함께 사용하면 더 편리하다.
// replace 메서드는 기본적인 정규식을 함께 사용함
let text = "Please visit Microsoft!";
let newText = text.replace(/MICROSOFT/i, "My tistory"); // 대소문자 구분X
console.log(newText); // Please visit My tistory!

text = "Please visit Microsoft and Microsoft!";
newText = text.replace(/Microsoft/g, "My tistory"); // 문자열 모두 대체
console.log(newText); // Please visit My tistory and My tistory!

 

 

 

 

문자열 대소문자 변환

  • toUpperCase() - 대문자로 변환
  • toLowerCase() - 소문자로 변환

 

 

 

 

문자열 연결

  • concat(newStr, plusStr) - 2개 이상의 문자열을 결합(기존 문자열 변경 X, 새 문자열 반환)
text = "Hello" + " " + "World!";
text = "Hello".concat(" ", "World!");
// 같은 의미!

 

 

 

 

문자열 공백 제거

  • trim() - 문자열의 양 쪽 공백 제거
let trimText = "       오늘의 날씨 맑음 ";
console.log(trimText.trim()); // 오늘의 날씨 맑음

 

 

 

 

문자열 추가

문자열의 힌트 또는 전체 값 중 일부만 보여주고 싶은 경우 사용

  • padStart(length, newChar) - 문자열 앞 쪽으로 newChar이 length만큼 추가된다.
  • padEnd(length, newChar) - 문자열 뒤 쪽으로 newChar이 length만큼 추가된다.

 

 

 

 

문자열 지정 위치 문자 반환

  • charAt(index) - 지정 index에 있는 문자를 반환
  • string[index] - 배열과 비슷하게 보이지만 배열은 아니다. readonly!
// index의 값이 고정적일 때 값을 추출해서 판단하는 로직에 많이 사용
let idNum = 880818-1234567
let genNum = idNum.charAt(7);
console.log(genNum); // 1

 

 

 

 

문자열 위치 찾기

지정된 문자열의 위치(index) 반환

  • indexOf("str", index) - 특정 문자("str")가 처음으로 등장하는 index 반환. 두 번째 매개변수는 문자를 찾기 시작할 index 지정.
  • lastIndexOf("str", index) - 특정 문자("str")가 마지막으로 등장하는 index 반환. 두 번째 매개변수는 문자를 찾기 시작할 index 지정.

 

 

 

 

지정 문자열 검색

지정 문자열이 시작과 끝으로 존재하는지 여부를 boolean 값으로 반환

  • startsWith(searchvalue, start) - 문자열이 지정된 값으로 시작하면 true. 두 번째 매개변수는 검색 시작 index이다.
  • endsWith(searchvalue, length) - 문자열이 지정된 값으로 끝나면 true. 두 번째 매개변수는 '시작'부터의 길이이다.

 

 

 

 

지정 문자열 포함 여부

  • includes() - 문자열에 지정된 값이 포함되어 있으면 true 반환. 2번째 인수로 검색 시작 위치를 설정할 수 있다.
let text = "Hello world, welcome to the universe.";
text.includes("world"); // true

 

 

 

 

정규 표현식을 이용한 문자열 조작

  • search(/str/flag) - 해당 문자열에서 인수로 전달받은 정규 표현식과 일치하는 첫 번째 문자열의 인덱스를 반환, 찾지 못하면 -1 반환.
    • indexOf()와 다른 점은? search()는 시작 위치를 지정할 수 없다. indexOf()는 정규표현식을 사용할 수 없다.
let str = "Please locate where 'locate' occurs!";
str.search(/Locate/i); // 7

 

  • match(/str/flag) - 해당 문자열에서 인수로 전달받은 정규 표현식과 일치하는 문자열을 찾아서 하나의 배열로 반환
let text = "The rain in SPAIN stays mainly in the plain";
text.match(/ain/g); // [ain, ain, ain]

 

  • i - 대소문자 구별하지 않고 검색
  • g - 일치하는 모든 부분 검색
  • m - 문자열이 여러 줄이어도 그대로 검색

 

 

 

 

 

※ 참고 자료

https://www.w3schools.com/js/js_string_methods.asp

http://www.tcpschool.com/javascript/js_standard_stringMethod