Back

str.startsWith()

str.startsWith()

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 str.startsWith() with the following snippet:

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

A more robust and optimized Polyfill is available str.startsWith">on GitHub by Mathias Bynens.


  Created by Mozilla Contributors, license: CC-BY-SA 2.5