--- title: String.prototype.startsWith() slug: Web/JavaScript/Reference/Global_Objects/String/startsWith translation_of: Web/JavaScript/Reference/Global_Objects/String/startsWith ---
{{JSRef}}

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
{{SpecName('ES6', '#sec-string.prototype.startswith', 'String.prototype.startsWith')}} {{Spec2('ES6')}} Initial definition.

Khả năng tương thích với Browser

{{CompatibilityTable}}
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}}

Xem thêm