String methods 정리

이예빈·2022년 6월 27일
0

JavaScript

목록 보기
6/26
post-thumbnail

1. string.indexOf(searchValue)

  • arguments: 찾고자 하는 문자열
  • return value: 처음으로 일치하는 index값, 없을 경우 -1 반환
  • lastIndexOf는 문자열 뒤에서부터 찾음
'Blue Whale'.indexOf('Blue');          // 0
'Blue Whale'.indexOf('blue');          // -1
'Blue Whale Whale'.indexOf('Whale');   // 5
'canal'.lastIndexOf('a');              // 3

2. string.includes(searchValue)

  • arguments: 찾고자 하는 문자열
  • return value: Boolean type
'Blue Whale'.includes('Blue'); // true
'Blue Whale'.includes('blue'); // false

3. string.split(seperator)

  • arguments: 분리 기준이 될 문자열
  • return value: 분리된 문자열이 포함된 배열
  • csv 형식을 처리할 때 유용
let str = 'Hello from the other side';
str.split(' ');

// ['Hello', 'from', 'the', 'other', 'side']

4.string.substring(start, end)

  • arguments: 시작 index, 끝 index (순서는 상관 없음)
  • return value: 시작과 끝 index 사이의 문자열
let str = 'abcdefghij';
str.substring(0, 3);  // 'abc'
str.substring(3, 0);  // 'abc'
str.substring(-1, 4); // 'abcd'  // 음수는 0으로 취급
str.substring(0, 20); // 'abcdefghij'  // length를 이상의 값인 경우 전체 string 출력
str.substring(6);     // 'ghij'  // end 값이 생략될 경우 문자열 끝까지 출력

5. string.slice()

  • substring과 비슷하지만 다르다.
let str = 'abcdefghij';
str.substring(3, 0); // 'abc'
str.slice(3, 0);     // ''
 -> substring과 slice가 비슷하지만 다른점!
   
str.slice(0, 3);     // 'abc'

6. string.trim()

  • 문자 양 끝의 공백 제거
let greeting = '      Hello world!      ';
greeting.trim();  // 'Hello world!'
profile
temporary potato

0개의 댓글