★ wanayoo — archive 1999 https://developer.mozilla.org/vi/docs/Web/JavaScript/Reference/Global_Objects/String/startsWithNouvelle recherche | Portail wanayoo

Join MDN and developers like you at Mozilla's View Source conference, November 2-4 in Portland, Oregon. Learn more at https://viewsourceconf.org/.

Our volunteers haven't translated this article into Tiếng Việt yet. Join us and help get the job done!

This is a new technology, part of the ECMAScript 2015 (ES6) standard.
This technology's specification has been finalized, but check the compatibility table for usage and implementation status in various browsers.

The startsWith() method determines whether a string begins with the characters of another string, returning true or false as appropriate.

Syntax

str.startsWith(searchString[, position])

Parameters

searchString
The characters to be searched for at the start of this string.
position
Optional. The position in this string at which to begin searching for searchString; defaults to 0.

Description

This method lets you determine whether or not a string begins with another string.

Examples

Using 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

This method has been added to the ECMAScript 6 specification and may not be available in all JavaScript implementations yet. However, you can polyfill String.prototype.startsWith() with the following snippet:

if (!String.prototype.startsWith) {
  String.prototype.startsWith = function(searchString, position) {
    position = position || 0;
    return this.indexOf(searchString, position) === position;
  };
}

A more robust and optimized Polyfill is available on GitHub by Mathias Bynens.

Specifications

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'String.prototype.startsWith' in that specification.
Standard Initial definition.

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 41 17 (17) Not supported 41 9
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support Not supported 36 17.0 (17) Not supported Not supported Not supported

See also

Hide Sidebar