startsWith()
메서드는 특정 문자로 시작하는지 확인해서 결과를 불리언으로 반환한다.
str.startsWith(searchString)
str.startsWith(searchString, position)
option
대상 문자열이 주어진 문자로 시작하면 true, 아니면 false를 반환한다.
문자열 123을 찾는다.
const str = "123455";
console.log(str.startsWith("123")); // true
아무것도 전달하지 않거나 undefined를 전달하면 문자열 "undefined"를 찾는다.
const str = "undefined";
console.log(str.startsWith()); // true
console.log(str.startsWith(undefined)); // true
숫자를 전달하면 암묵적으로 문자열로 변환된다.
const str = "12345";
console.log(str.startsWith(123)); // true
마찬가지로 불리언을 전달해도 암묵적으로 문자열로 변환된다.
const str = "true";
console.log(str.startsWith(true)); // true
정규표현식을 전달하면 TypeError가 발생한다.
const str = "Hello world!";
console.log(str.startsWith(/./g)); // TypeError: First argument to String.prototype.startsWith must not be a regular expression
두번째 인수에 인덱스를 전달하면 탐색을 시작할 위치를 지정할 수 있다.
const str = "000123000";
console.log(str.startsWith("123", 3)); // true
endsWith()
메서드는 지정된 문자열로 끝나는지 여부를 확인해서 결과를 불리언으로 반환한다.
str.endsWith(searchString)
str.endsWith(searchString, endPosition)
option
주어진 문자가 문자열 끝에 있으면 true, 아니면 false
// 뒤에서 "끝" 문자 찾기
const end = "00000끝";
console.log(end.endsWith("끝")); // true
console.log(end.endsWith("끝", end.length)); // true
console.log(end.endsWith("끝", 6)); // true
// 뒤에서 "중간" 문자 찾기
const middle = "000중간000";
console.log(middle.endsWith("중간", 5)); // true
console.log(middle.endsWith("중간", 4)); // false
📌 참고