Comprobar si la cadena comienza con algo? [duplicar]


Posible Duplicado:
Inicio de Javascript con

Sé que puedo hacer como ^= para ver si un id comienza con algo, y traté de usarlo para esto, pero no funcionó... Básicamente, estoy recuperando la url y quiero establecer una clase para un elemento para nombres de ruta que comiencen de cierta manera...

Así que,

var pathname = window.location.pathname;  //gives me /sub/1/train/yonks/459087

Quiero asegurarme de que para cada ruta que comienza con /sub/1, puedo establecer una clase para un elemento...

if(pathname ^= '/sub/1') {  //this didn't work... 
        ... 
Author: Community, 2009-11-20

6 answers

Use stringObject.subcadena

if (pathname.substring(0, 6) == "/sub/1") {
    // ...
}
 356
Author: Philip Reynolds,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-20 19:31:36
String.prototype.startsWith = function(needle)
{
    return this.indexOf(needle) === 0;
};
 175
Author: Ricardo Peres,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-08 16:58:00

Puede usar cadena.match () y una expresión regular para esto también:

if(pathname.match(/^\/sub\/1/)) { // you need to escape the slashes

string.match() devolverá una matriz de subcadenas coincidentes si se encuentra, de lo contrario null.

 82
Author: Cros,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-11 22:42:32

Una función un poco más reutilizable:

beginsWith = function(needle, haystack){
    return (haystack.substr(0, needle.length) == needle);
}
 36
Author: RobKohr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-06 23:15:25

Primero, extendamos el objeto string. Gracias a Ricardo Peres por el prototipo, creo que usar la variable 'string' funciona mejor que 'needle' en el contexto de hacerlo más legible.

String.prototype.beginsWith = function (string) {
    return(this.indexOf(string) === 0);
};

Entonces lo usas así. Precaución! Hace que el código sea extremadamente legible.

var pathname = window.location.pathname;
if (pathname.beginsWith('/sub/1')) {
    // Do stuff here
}
 22
Author: Tim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-19 06:31:54

Echa un vistazo a JavaScript substring() método.

 2
Author: rochal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-03 23:12:45