Có hai cách tìm chuỗi con (substring) trong chuỗi (string). Cách 1: dùng indexOf(), cách 2: dùng ES6 includes(). Thảo luận chi tiết.
indexOf()
Cú pháp
indexOf(chuỗi_con);
Kiểm tra vị trí (index) của chuỗi con. Nếu tìm thấy (index !== -1) trả true, ngược lại false. Phương thức phân biệt chữ hoa thường (case sensitive).
Ví dụ
<html> <body> <script>
var company = "Tutorix";
document.write(company.indexOf('Tutor') !== -1);
document.write("</br>");
document.write(company.indexOf('tutor') !== -1);
</script> </body> </html>
Kết quả
true false
includes()
Cú pháp
includes(chuỗi_con);
Khác với indexOf(), phương thức này kiểm tra chuỗi con có tồn tại hay không. Nếu có trả true, không thì false. Cũng phân biệt chữ hoa thường. Cần cung cấp chuỗi chính xác.
Ví dụ
<html> <body> <script>
var company = "tutorialspoint";
document.write(company.includes('Tutor'));
document.write("</br>");
document.write(company.includes('point'));
</script> </body> </html>
Kết quả
false true