JS - String method [startsWith(), endsWith(), includes()]

JUGNMIN LEE·2021년 1월 13일
0

javascript

목록 보기
11/13
post-thumbnail

ES6 에서 추가된 몇가지 string method가 있다
그 중에서 자주 쓰일 것 같아 포스팅 해본다.

문자열 값을 원하는 값이 들어가 있는지 판별한 후 boolean 값으로 return한다

startWith()

~로 시작하는지 알려주는 녀석이며 사용 구문은 아래와 같다

str.startWith(searchString, position)
(searchString : 문자열의 시작 지점에서 탐색할 문자열)
(position : searchString을 탐색할 위치 기본값은 0)

사용 가능한 범위는 string 이며 예제를 통해 사용법을 확인하자.

const str = '안녕하세요 저는 냉면을 좋아합니다.';

console.log(str.startWith('안녕')); // true
console.log(str.startWith('냉면을')); // false
console.log(str.startWith('냉면을', 9)); // true

endsWith()

~로 끝나는지 알려주는 녀석이며 사용 구문은 아래와 같다

str.endsWith(searchString, length);
(searchString : 문자열 끝이 특정 문자열로 끝나는지 찾기를 원하는 문자열)
(length : 찾고자 하는 문자열의 길이값, 기본값은 문자열 전체 길이)

사용 가능한 범위는 string 이며 예제를 통해 사용법을 확인하자.

const str = '안녕하세요 저는 냉면을 좋아합니다.';

console.log(str.endsWith('좋아합니다.')); // true
console.log(str.endsWith('안녕')); // false
console.log(str.endsWith('안녕', 2)); // true

includes

~를 포함하고 있는지 알려주는 녀석이며
사용범위는 arr, string 둘다 사용가능하다

arr 사용 구문은 아래와 같다

arr.includes(valueFind, formindex);
(valueFind : 탐색할 요소 문자나 문자열을 비교함, 대소문자 구분함)
(formindex : 이 배열에서 searchElement 검색을 시작할 위치 또한
특별하게 음의값을 array.length + fromindex의 인덱스를 asc로 인식하여 검색함 기본값은 0이다.)

[1,2,3].includes(4);
[1,2,3].includes(3, 3);
[1,2,3].includes(3, -1);

[1, 2, 3] => 배열
0 1 2 => index 번호

array.length + fromIndex를 생각 해본다면
2번째 줄 코드에선, 3+3 한곳부터 숫자 3을 검색할테니 false
3번째 줄 코드에선 3+ (-1) 일테니, 3은 존재합니다 true

따라서 fromIndex 가 배열의 길이보다 같거나 크다면 false를 return


String 사용 구문은 아래와 같다

string.includes(searchString, position);
(searchString : 이 문자열에서 찾을 다른 문자열)
(position : searchString을 찾기 시작할 위치, 기본값 0)

include() 메서드는 대소문자를 구별하기에 영어로 확인하자

const test = 'Do not try to be original, just try to be good';

console.log(test.includes('Do not'));
console.log(test.includes('good'));
console.log(test.includes('javascript'));
console.log(test.includes('Do not', 1));
console.log(test.includes('DO NOT'));
profile
Frontend Developer

0개의 댓글