String.prototype.includes()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2015.
Phương thức includes() của các giá trị String thực hiện tìm kiếm phân biệt chữ hoa chữ thường để xác định xem một string đã cho có thể được tìm thấy trong string này hay không, trả về true hoặc false tùy trường hợp.
Try it
const sentence = "The quick brown fox jumps over the lazy dog.";
const word = "fox";
console.log(
`The word "${word}" ${
sentence.includes(word) ? "is" : "is not"
} in the sentence`,
);
// Expected output: "The word "fox" is in the sentence"
Cú pháp
includes(searchString)
includes(searchString, position)
Tham số
searchString-
Một string cần tìm trong
str. Không thể là regex. Tất cả các giá trị không phải regex được ép kiểu thành string, vì vậy bỏ qua hoặc truyềnundefinedkhiếnincludes()tìm kiếm string"undefined", điều này hiếm khi bạn muốn. positionOptional-
Vị trí trong string bắt đầu tìm kiếm
searchString. (Mặc định là0.)
Giá trị trả về
true nếu search string được tìm thấy ở bất kỳ đâu trong string đã cho, bao gồm khi searchString là string rỗng; ngược lại là false.
Ngoại lệ
Mô tả
Phương thức này cho phép bạn xác định xem một string có bao gồm một string khác hay không.
Phân biệt chữ hoa chữ thường
Phương thức includes() phân biệt chữ hoa chữ thường. Ví dụ, biểu thức sau trả về false:
"Blue Whale".includes("blue"); // returns false
Bạn có thể giải quyết vấn đề này bằng cách chuyển đổi cả string gốc và search string thành chữ thường:
"Blue Whale".toLowerCase().includes("blue"); // returns true
Ví dụ
>Sử dụng includes()
const str = "To be, or not to be, that is the question.";
console.log(str.includes("To be")); // true
console.log(str.includes("question")); // true
console.log(str.includes("nonexistent")); // false
console.log(str.includes("To be", 1)); // false
console.log(str.includes("TO BE")); // false
console.log(str.includes("")); // true
Đặc tả
| Specification |
|---|
| ECMAScript® 2027 Language Specification> # sec-string.prototype.includes> |