Come sapere che una stringa inizia / finisce con una stringa specifica in jQuery?


206

Voglio sapere se una stringa inizia con il carattere / stringa specificato o termina con esso in jQuery.

Per esempio:

var str = 'Hello World';

if( str starts with 'Hello' ) {
   alert('true');
} else {
   alert('false');
}

if( str ends with 'World' ) {
   alert('true');
} else {
   alert('false');
}

Se non c'è alcuna funzione, allora qualche alternativa?



2
Sì, o non usi ancora ES6 se hai utenti che usano IE più vecchio di Edge.
— Antares42,

Risposte:


388

Un'opzione è utilizzare le espressioni regolari:

if (str.match("^Hello")) {
   // do this if begins with Hello
}

if (str.match("World$")) {
   // do this if ends in world
}

1
in jQuery ho provato str.starttsWith ('un po' di stringa di controllo .. ') questo mi ha dato un errore dicendo: inizia con metodo non trovato .. :( ma str.match ha funzionato. Grazie per la tua risposta
— Débora il

2
Fai solo attenzione che la stringa che stai controllando non contenga alcun carattere riservato regex.
— notte del

23
Il passaggio di un oggetto regex invece di una stringa regex sembra risolvere il problema @nokturnal cita: str.match(/^Hello/)Ma la forma /regex/.test(str)è ancora meglio per questo caso particolare, per stackoverflow.com/questions/10940137/...
— CrazyPyro

Ciò restituirebbe una stringa corrispondente, ma non un valore booleano.
— RajKumar Samala,

var isUnavailable = $("#StatusId option:selected").text().match("^Unavailable - ");- perché questo restituisce null quando l'opzione selezionata è "Non disponibile - Altro"?
— egmfrs,

96

Per iniziare, puoi usare indexOf:

if(str.indexOf('Hello') == 0) {

...

arbitro

e puoi fare i calcoli in base alla lunghezza della stringa per determinare "endwith".

if(str.lastIndexOf('Hello') == str.length - 'Hello'.length) {

11
potresti voler usare lastIndexOf()il fine con;)
— Reigel,

Attenzione, IndexOf non è supportato nel browser IE8. Lo stesso con lastIndexOf.
— Pedro Lopes,

1
Mi scuso per la confusione. Mi riferivo ad Array.prototype.indexOf () che è supportato solo per iE9 + e non String.prototype.indexOf () che è IE4 +
— Pedro Lopes

3
Una risposta molto più sicura rispetto all'uso delle espressioni regolari per un caso d'uso così semplice. Probabilmente dovrebbe essere accettata la risposta.
— AntonChanning,

1
Il codice per "endwith" è difettoso. Quando si controlla una stringa che non appare nella stringa e che ha la lunghezza = (parola - 1). Per esempio. ("1234".lastIndexOf('Hello') == "1234".length - 'Hello'.length)risulta vero.
— Nick Russler,

23

Non è necessario che jQuery lo faccia. Potresti codificare un wrapper jQuery ma sarebbe inutile, quindi dovresti usarlo meglio

var str = "Hello World";

window.alert("Starts with Hello ? " + /^Hello/i.test(str));        

window.alert("Ends with Hello ? " + /Hello$/i.test(str));

poiché il metodo match () è obsoleto.

PS: il flag "i" in RegExp è facoltativo e indica la distinzione tra maiuscole e minuscole (quindi tornerà vero anche per "ciao", "hello", ecc.).


2
Potete fornire un link alla documentazione su match () che è deprecato? Una rapida ricerca su Google non restituisce nulla.
— Cavyn VonDeylen,

1
L'ho letto online qualche anno fa, temo di non riuscire più a trovare esattamente dove.
— Sebastien P.

16

Non hai davvero bisogno di jQuery per tali compiti. Nella specifica ES6 hanno già i metodi pronti per iniziare con e termina con .

var str = "To be, or not to be, that is the question.";
alert(str.startsWith("To be"));         // true
alert(str.startsWith("not to be"));     // false
alert(str.startsWith("not to be", 10)); // true

var str = "To be, or not to be, that is the question.";
alert( str.endsWith("question.") );  // true
alert( str.endsWith("to be") );      // false
alert( str.endsWith("to be", 19) );  // true

Attualmente disponibile in FF e Chrome . Per i vecchi browser puoi usare i loro polyfill o substr


10

Puoi sempre estendere il Stringprototipo in questo modo:

//  Checks that string starts with the specific string
if (typeof String.prototype.startsWith != 'function') {
    String.prototype.startsWith = function (str) {
        return this.slice(0, str.length) == str;
    };
}

//  Checks that string ends with the specific string...
if (typeof String.prototype.endsWith != 'function') {
    String.prototype.endsWith = function (str) {
        return this.slice(-str.length) == str;
    };
}

E usalo in questo modo:

var str = 'Hello World';

if( str.startsWith('Hello') ) {
   // your string starts with 'Hello'
}

if( str.endsWith('World') ) {
   // your string ends with 'World'
}

2

ES6 ora supporta il metodo startsWith()e endsWith()per controllare l'inizio e la fine di strings. Se si desidera supportare i motori pre-es6, si consiglia di aggiungere uno dei metodi suggeriti al Stringprototipo.

if (typeof String.prototype.startsWith != 'function') {
  String.prototype.startsWith = function (str) {
    return this.match(new RegExp("^" + str));
  };
}

if (typeof String.prototype.endsWith != 'function') {
  String.prototype.endsWith = function (str) {
    return this.match(new RegExp(str + "$"));
  };
}

var str = "foobar is not barfoo";
console.log(str.startsWith("foob"); // true
console.log(str.endsWith("rfoo");   // true

Qualsiasi stringa che contiene caratteri che devono essere sottoposti a escape per l'utilizzo in una regex (ad esempio ()[].) interromperà i metodi di polyfill. Devi preparare le stringhe con una funzione regex-escape. O ancora meglio: usa un polyfill testato in battaglia dacore-js
— nirazul l'
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.