Sử dụng phương thức String.prototype.indexOf() để tìm vị trí xuất hiện đầu tiên của chuỗi con. Trả về -1 nếu không tìm thấy.
Cú pháp
string.indexOf(searchValue[, fromIndex])
searchValue: Chuỗi cần tìm.fromIndex(tùy chọn): Vị trí bắt đầu tìm (mặc định 0).
Ví dụ
<!DOCTYPE html>
<html>
<body>
<script>
var str = "Học vui, học làm, học chia sẻ!";
var idx1 = str.indexOf("Học");
document.write("Đầu tiên 'Học' tại: " + idx1 + "<br>"); // 0
var idx2 = str.indexOf("Học", 5);
document.write("Tìm từ index 5: " + idx2 + "<br>"); // 7
var idx3 = str.indexOf("xyz");
document.write("Không tìm thấy: " + idx3); // -1
</script>
</body>
</html>
Phương thức liên quan:
| Phương thức | Mô tả |
|---|---|
indexOf() | Tìm đầu tiên (trái → phải). |
lastIndexOf() | Tìm cuối cùng (phải → trái). |
search() | Tìm regex, trả index đầu tiên. |
includes() | ES6: trả true/false (dễ đọc hơn). |
ES6: includes() — Khuyến nghị cho kiểm tra tồn tại
"hello world".includes("world") // true
"hello world".includes("World") // false (case-sensitive)
"hello world".includes("world", 6) // false (từ index 6)
includes() đọc dễ hiểu hơn indexOf() !== -1.