--- title: String.prototype.startsWith() slug: Web/JavaScript/Reference/Global_Objects/String/startsWith translation_of: Web/JavaScript/Reference/Global_Objects/String/startsWith ---
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.
str.startsWith(searchString[, position])
searchString
position
searchString;
mặc định là 0.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.
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
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.
Specification | Status | Comment |
---|---|---|
{{SpecName('ES6', '#sec-string.prototype.startswith', 'String.prototype.startsWith')}} | {{Spec2('ES6')}} | Initial definition. |
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | {{CompatChrome("41")}} | {{CompatGeckoDesktop("17")}} | {{CompatNo}} | {{CompatChrome("41")}} | {{CompatSafari("9")}} |
Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | {{CompatNo}} | {{CompatChrome("36")}} | {{CompatGeckoMobile("17")}} | {{CompatNo}} | {{CompatNo}} | {{CompatNo}} |