startsWith()
method xác định liệu một chuỗi bắt đầu với các chữ cái của chuỗi khác hay không, trả về giá trị true hoặc false tương ứng.
Cú pháp
str.startsWith(searchString[, position])
Tham số
searchString
- Các ký tự cần tìm kiếm tại vị trí bắt đầu của chuỗi này.
position
- Tùy chọn. Vị trí trong chuỗi bắt đầu tìm kiếm cho
searchString;
mặc định là 0.
Miêu tả
Method này cho phép bạn xác định liệu một chuỗi có bắt đầu với chuỗi khác không.
Ví dụ
Cách sử dụng startsWith()
var str = 'To be, or not to be, that is the question.';
console.log(str.startsWith('To be')); // true
console.log(str.startsWith('not to be')); // false
console.log(str.startsWith('not to be', 10)); // true
Polyfill
Method này đã được thêm vào chỉ dẫn kỹ thuật ECMAScript 6 và có thể chưa có sẵn trong tất cả JavaScript implementations. Tuy nhiên, bạn có thể polyfill String.prototype.startWith() với snippet sau:
if (!String.prototype.startsWith) {
String.prototype.startsWith = function(searchString, position) {
position = position || 0;
return this.indexOf(searchString, position) === position;
};
}
Polyfill mạnh và được tối ưu hơn có sẵn trên GitHub bởi Mathias Bynens.
Hướng dẫn kỹ thuật
Specification | Status | Comment |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'String.prototype.startsWith' in that specification. |
Standard | Initial definition. |
Khả năng tương thích với Browser
We're converting our compatibility data into a machine-readable JSON format.
This compatibility table still uses the old format,
because we haven't yet converted the data it contains.
Find out how you can help!
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | 41 | 17 (17) | No support | 41 | 9 |
Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | No support | 36 | 17.0 (17) | No support | No support | No support |