Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ความสำคัญของเมธอด startsWith() ใน JavaScript

startsWith() (ES6) ตรวจสอบว่าสตริงขึ้นต้นด้วยข้อความที่กำหนด อ่านง่ายกว่า indexOf() === 0 รองรับพารามิเตอร์ที่ 2 สำหรับตำแหน่งเริ่มต้น

ตัวอย่าง indexOf() แบบเก่า

<html> <body> <script> 
    var text = 'Tutorialspoint'; 
    document.write(text.indexOf('T') === 0); 
</script> </body> </html>

ผลลัพธ์

true

ตัวอย่าง startsWith()

<html> <body> <script> 
    var text = 'Tutorialspoint'; 
    document.write(text.startsWith('Tu')); 
</script> </body> </html>

ผลลัพธ์

true

ตัวอย่าง ระบุตำแหน่งเริ่มต้น

<html> <body> <script> 
    var text = 'Tutorialspoint'; 
    document.write(text.startsWith('Tut', 0)); 
    document.write("<br>"); 
    document.write(text.startsWith('ut', 1)); 
    document.write("<br>"); 
    document.write(text.startsWith('t', 2)); 
</script> </body> </html>

ผลลัพธ์

true true true