My Profile Photo

El rincón de mautemático


Las Cosas son como deben, no como deberían Ser.


JavaScript: string startsWith()

If you ever need to know in your JavaScript application if a string starts with another string, you can just use new ECMAScript 6’s method: startsWith()

str.startsWith(searchString[, position]) will take:

  • as first parameter: searchString, the characters you want to know are or not at the beginning of str
  • as optional parameter: position the index you want the search to start.

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

Please keep in mind: old browsers do not implement startsWith(). Here you have a Polyfill for those old browsers:

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

See also

Please refer to MDN if you have any further questions on this.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith#Syntax

There you will get not only up-to-date documentation for startsWith(), but also references to related methods and a more robust Polyfill.