--- title: String.prototype.startsWith() slug: Web/JavaScript/Reference/Global_Objects/String/startsWith translation_of: Web/JavaScript/Reference/Global_Objects/String/startsWith original_slug: Web/JavaScript/Referencia/Objectes_globals/String/startsWith ---
El mètode startsWith() determina si un string comença amb els caràcters d'un altre string, retornant true o false depenent d'això.
str.startsWith(stringAcercar[, posició])
stringAcercarposicióstringAcercar; per defecte és 0.Aquest mètode us permet determinar si un string comença amb un altre string.
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
Aquest mètode va ser afegit a l'especificació ECMAScript i pot no estar disponible encara a totes les implementacions de JavaScript. No obstant, la funció següent emula el comportament de String.prototype.startsWith():
if (!String.prototype.startsWith) {
String.prototype.startsWith = function(searchString, position) {
position = position || 0;
return this.indexOf(searchString, position) === position;
};
}
Trobareu una funció Polyfill més robusta i optimitzada al GitHub de Mathias Bynens.
| Especificació | Estat | Comentaris |
|---|---|---|
| {{SpecName('ES6', '#sec-string.prototype.startswith', 'String.prototype.startsWith')}} | {{Spec2('ES6')}} | Definició inicial. |
| Característica | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Suport bàsic | {{CompatChrome("41")}} | {{CompatGeckoDesktop("17")}} | {{CompatNo}} | {{CompatChrome("41")}} | {{CompatNo}} |
| Característica | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| Suport bàsic | {{CompatNo}} | {{CompatChrome("36")}} | {{CompatGeckoMobile("17")}} | {{CompatNo}} | {{CompatNo}} | {{CompatNo}} |