string.startsWith() - jamm0316/programers-codingtest GitHub Wiki

1. κ°œμš”

λ¬Έμžμ—΄μ΄ νŠΉμ • 문자 λ˜λŠ” λ¬Έμžμ—΄λ‘œ μ‹œμž‘ν•˜λŠ”μ§€ 확인할 λ•Œ μ‚¬μš©. 이 λ©”μ„œλ“œλŠ” λŒ€μ†Œλ¬Έμžλ₯Ό κ΅¬λΆ„ν•˜λ©°, νŠΉμ • μœ„μΉ˜μ—μ„œλΆ€ν„° μ‹œμž‘ν•˜λŠ”μ§€ 확인할 μˆ˜λ„ 있음.
κ·Έ κ²°κ³Όλ₯Ό boolean κ°’μœΌλ‘œ λ°˜ν™˜ν•©λ‹ˆλ‹€.

2. κΈ°λ³Έ ν˜•νƒœ

string.startsWith(searchString, position)

3. λ§€κ°œλ³€μˆ˜

a. searchString

  • ν™•μΈν•˜λ €λŠ” λ¬Έμžμ—΄. ν•„μˆ˜ λ§€κ°œλ³€μˆ˜μž…λ‹ˆλ‹€.

b. position

  • 확인을 μ‹œμž‘ν•  μœ„μΉ˜. 기본값은 0μž…λ‹ˆλ‹€. 선택적 λ§€κ°œλ³€μˆ˜μž…λ‹ˆλ‹€.

c. λ°˜ν™˜κ°’

  • boolean: 주어진 λ¬Έμžμ—΄μ΄ searchString으둜 μ‹œμž‘ν•˜λ©΄ true, 그렇지 μ•ŠμœΌλ©΄ falseλ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.

4. μ‚¬μš© μ˜ˆμ‹œ

// κΈ°λ³Έ μ‚¬μš© μ˜ˆμ‹œ
let str = "Hello, world!";
console.log(str.startsWith("Hello")); // true
console.log(str.startsWith("world")); // false

// νŠΉμ • μœ„μΉ˜μ—μ„œ μ‹œμž‘ 확인
console.log(str.startsWith("world", 7)); // true

// λŒ€μ†Œλ¬Έμž ꡬ뢄
console.log(str.startsWith("hello")); // false

더 λ§Žμ€ μ˜ˆμ‹œ

// 배열을 μ‚¬μš©ν•œ μ˜ˆμ‹œ
let phoneNumbers = ["119", "97674223", "1195524421"];

phoneNumbers.sort();

for (let i = 0; i < phoneNumbers.length - 1; i++) {
    if (phoneNumbers[i + 1].startsWith(phoneNumbers[i])) {
        console.log(`"${phoneNumbers[i]}" is a prefix of "${phoneNumbers[i + 1]}"`);
    }
}

// μ‹€ν–‰ κ²°κ³Ό:
// "119" is a prefix of "1195524421"