มี 2 วิธีหลัก: indexOf() และ includes() (ES6) ทั้งคู่ case-sensitive
indexOf()
indexOf(str);
คืนดัชนี หากไม่พบคืน -1 ตรวจสอบด้วย !== -1
ตัวอย่าง
<html> <body> <script>
var company = "Tutorix";
document.write(company.indexOf('Tutor') !== -1);
document.write("<br>");
document.write(company.indexOf('tutor') !== -1);
</script> </body> </html>
ผลลัพธ์
true false
includes() (ES6)
includes(str);
คืน true/false โดยตรง อ่านง่ายกว่า
ตัวอย่าง
<html> <body> <script>
var company = "tutorialspoint";
document.write(company.includes('Tutor'));
document.write("<br>");
document.write(company.includes('point'));
</script> </body> </html>
ผลลัพธ์
false true