String.prototype.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ò.
Sintaxi
str.startsWith(stringAcercar[, posició])
Paràmetres
stringAcercar
- Els caràcters a cercar al començament d'aquest string.
posició
- Opcional. La posició dins el string a la qual es començarà a cercar per a trobar
stringAcercar
; per defecte és 0.
Descripció
Aquest mètode us permet determinar si un string comença amb un altre string.
Exemples
Utilitzar 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
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.
Especificacions
Especificació | Estat | Comentaris |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'String.prototype.startsWith' in that specification. |
Standard | Definició inicial. |
Compatibilitat amb navegadors
We're converting our compatibility data into a machine-readable JSON format.
This compatibility table still uses the old format,
because we haven't yet converted the data it contains.
Find out how you can help! (en-US)
Característica | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Suport bàsic | 41 | 17 (17) | No support | 41 | No support |
Característica | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Suport bàsic | No support | 36 | 17.0 (17) | No support | No support | No support |