Study/JavaScript

[JS] startsWith & endsWith

taecongs 2023. 12. 22. 17:24

알고있으면 좋은 Javascript Tip✨


startsWith & endsWith란 무엇인가?

  • startsWith
    1. 확인하고자 하는 문자열에서 특정 문자열로 시작하는지 확인하는 메서드이다.
    2. 특정 문자열이 있는 경우에는 true를 반환하고, 그렇지 않은 경우에는 false 를 반환한다.
    3. 검색해야 할 문자열은 필수 요소이며, 문자열은 대소문자를 구분한다.
    4. 문자열의 길이도 옵션에 포함되고, 문자열 길이를 넣지 않는 경우에는 전체 문자열을 대상으로 검색한다.
  • endsWith
    1. 확인하고자 하는 문자열에서 특정 문자열로 끝나는지 확인하는 메서드이다.
    2. 특정 문자열이 있는 경우에는 true를 반환하고 그렇지 않은 경우에는 false를 반환한다.
    3. 검색해야 할 문자열은 필수 요소이며, 문자열은 대소문자를 구분한다.
    4. 문자열의 길이도 옵션에 포함되고, 문자열 길이를 넣지 않는 경우에는 전체 문자열을 대상으로 검색한다.

 

(1) startsWith()

// startsWith 문법 
문자열.startsWith('검색하고자 하는 문자', length);

const str = "Hello, world!";

console.log(str.startsWith('H'));      // true
console.log(str.startsWith('h'));      // false
console.log(str.startsWith('H', 5));   // false

 

(2) endsWith()

// endsWith 문법 
문자열.endsWith('검색하고자 하는 문자', length);

const str = "Hello, world!";

console.log(str.endsWith('!'));         // true
console.log(str.endsWith('o', 5));      // true
console.log(str.endsWith('A'));         // false