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

'Study > JavaScript' 카테고리의 다른 글

[JS] Axios  (0) 2024.01.10
[JS] every & some  (0) 2023.12.26
[JS] 공백 제거(trim, trimStart, trimLeft, trimEnd, trimRight)  (0) 2023.12.20
[JS] Early Return  (0) 2023.11.20
[JS] undefined & null  (0) 2023.10.26