2016-05-31 8 views
7

sto cercando di confrontare due stringhe in JavaScript utilizzando EndsWith(), comeJavaScript terminaCome non funziona in IEv10?

var isValid = string1.endsWith(string2); 

Sta funzionando bene in Google Chrome e Mozilla. Quando viene a IE viene generato un errore console come segue

SCRIPT438: Object doesn't support property or method 'endsWith' 

Come posso risolverlo?

risposta

9

Metodo endsWith() non supportato in IE. Controllare browser compatibility here.

È possibile utilizzare l'opzione polyfill tratto da MDN documentation:

if (!String.prototype.endsWith) { 
    String.prototype.endsWith = function(searchString, position) { 
     var subjectString = this.toString(); 
     if (typeof position !== 'number' || !isFinite(position) 
      || Math.floor(position) !== position || position > subjectString.length) { 
     position = subjectString.length; 
     } 
     position -= searchString.length; 
     var lastIndex = subjectString.indexOf(searchString, position); 
     return lastIndex !== -1 && lastIndex === position; 
    }; 
} 
+0

Essa aiuta a sapere che questo script può essere posizionato ovunque. Idealmente viene caricato come la pagina viene caricata troppo in modo che sia resa disponibile per tutte le altre funzioni –

+0

Trova la risposta semplificata qui https://stackoverflow.com/questions/37544376/javascript-endswith-is-not-working-in-iev10 # risposta-37545037 –

4

ho trovato la risposta più semplice,

Tutto quello che devi fare è quello di definire il prototipo

if (!String.prototype.endsWith) { 
    String.prototype.endsWith = function(suffix) { 
    return this.indexOf(suffix, this.length - suffix.length) !== -1; 
    }; 
} 
1

è generalmente cattiva pratica per estendere il prototipo di un oggetto JavaScript nativo. Vedi qui - Why is extending native objects a bad practice?

È possibile utilizzare un controllo semplice come questo che funziona cross-browser:

var isValid = (string1.lastIndexOf(string2) == (string1.length - string2.length))