2010-09-15 13 views
173

Quiero saber si una cadena comienza con el carácter/serie especificado o termina con jQuery.¿Cómo saber que una cadena comienza/termina con una cadena específica en jQuery?

Por ejemplo:

var str = 'Hello World'; 

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

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

Si no hay ninguna función que cualquier alternativa?

+0

Utilice [ES6 nuevas características] (http://stackoverflow.com/a/25797279/1090562) –

+1

Sí, bueno, o no utilice ES6 sin embargo, si tiene usuarios que utilizan IE mayores de Edge. – Antares42

Respuesta

329

Una opción es el uso de expresiones regulares:

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

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

en jQuery Probé str.startsWith ('some checking string ..') esto me dio un error diciendo: startsWith método no encontrado ... :(pero str.match funcionó. Gracias por su respuesta –

+2

Solo tenga cuidado con la cadena que está inspecting no contiene ningún carácter reservado de expresiones regulares. – nokturnal

+16

Pasar un objeto regex en lugar de una cadena de expresiones regulares parece resolver el problema @nokturnal menciona: 'str.match (/^Hello /)' Pero la forma '/regex/.test (str) 'es aún mejor para este caso particular, por http://stackoverflow.com/questions/10940137/regex-test-vs-string-match-to-know-if-a-string-matches-a-regular- expresión – CrazyPyro

84

Para startswith, puede usar indexOf:

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

...

ref

y usted puede hacer las cuentas en base a la longitud de cadena para determinar 'endswith'.

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

es posible que desee utilizar 'lastIndexOf()' para el final con;) – Reigel

+0

Cuidado, IndexOf no es compatible con el navegador IE8. Lo mismo con lastIndexOf. –

+1

Pido disculpas por la confusión. Me estaba refiriendo a Array.prototype.indexOf() que solo es compatible con iE9 + y no con String.prototype.indexOf() que es IE4 + –

19

No hay necesidad de jQuery para hacer eso. Podría codificar un envoltorio de jQuery, pero sería inútil lo que debe utilizar mejor

var str = "Hello World"; 

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

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

como está obsoleto el método match().

PD: la bandera "i" en RegExp es opcional y no distingue entre mayúsculas y minúsculas (por lo que también será verdadera para "hola", "hEllo", etc.).

+1

+1 Probado aquí: http://jsfiddle.net/zTLrU/ – NAVEED

+1

+1 Gracias por incluir la parte "insensible a mayúsculas y minúsculas" –

+2

Puede proporcionar un enlace al docum entation on match() está en desuso? Una búsqueda rápida en Google no devuelve nada. –

10

Realmente no necesita jQuery para tales tareas. En la especificación ES6 ya tienen los métodos startsWith y endsWith listos para usar.

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 

Currently available in FF and Chrome. Para los navegadores antiguos puede utilizar sus polyfills o substr

+3

No funciona en IE10 u 11 –

7

siempre se puede extender prototipo de cadena como esta:

// 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; 
    }; 
} 

y utilizar de esta manera

var str = 'Hello World'; 

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

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

es6 ahora es compatible con el método startsWith() y endsWith() para verificar el comienzo y el final de string s. Si desea admitir motores prees6, le recomendamos que agregue uno de los métodos sugeridos al prototipo String.

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(startsWith("foob"); // true 
console.log(endsWith("rfoo"); // true 
Cuestiones relacionadas