Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Ahora ejecuto un bucle for que atraviesa la matriz y debería devolver todas las aves. ¿Qué comparación tendría
sentido aquí?
Animals == "bird*" fue mi primera idea pero no funciona. ¿Hay alguna forma de usar el operador * (o hay algo
similar para usar?
40
xqz313 7 oct. 2014
Creo que quisiste decir algo como "*" (estrella) como comodín, por ejemplo:
"a * b" => todo lo que comienza con "a" y termina con "b"
"a *" => todo lo que comienza con "a"
//Short code
function matchRuleShort(str, rule) {
var escapeRegex = (str) => str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
return new RegExp("^" + rule.split("*").map(escapeRegex).join(".*") + "$").test(str);
}
//Explanation code
function matchRuleExpl(str, rule) {
// for this solution to work on any string, no matter what characters it has
var escapeRegex = (str) => str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
// "^" => Matches any string with the following at the beginning of it
// "$" => Matches any string with that in front at the end of it
rule = "^" + rule + "$"
//Create a regular expression object for matching string
var regex new RegExp
R E (rule
l );
var regex = new RegExp(rule);
//Examples
alert(
"1. " + matchRuleShort("bird123", "bird*") + "\n" +
"2. " + matchRuleShort("123bird", "*bird") + "\n" +
"3. " + matchRuleShort("123bird123", "*bird*") + "\n" +
"4. " + matchRuleShort("bird123bird", "bird*bird") + "\n" +
"5. " + matchRuleShort("123bird123bird123", "*bird*bird*") + "\n" +
"6. " + matchRuleShort("s[pe]c 3 re$ex 6 cha^rs", "s[pe]c*re$ex*cha^rs") + "\n" +
"7. " + matchRuleShort("should not match", "should noo*oot match") + "\n"
);
79
Spen 4 sept. 2015
Debe usar RegExp (son increíbles), una solución fácil es:
if( /^bird/.test(animals[i]) ){
// a bird :D
Qué salidas:
bird1
bird2
Básicamente, está verificando cada elemento de la matriz para ver si las primeras cuatro letras son 'pájaro'. Esto
supone que 'pájaro' siempre estará al frente de la cadena.
Entonces, digamos que obtienes un nombre de ruta de una URL:
Digamos que estás en bird1? = Letsfly: puedes usar este código para verificar la URL:
var listOfUrls = [
"bird1?=letsfly",
"bird",
"pigs?=dontfly",
]
Lo anterior coincidiría con el primero con las URL, pero no con el tercero (no el cerdo). Puede cambiar fácilmente
url.substring(0,4) con una expresión regular, o incluso con otro método javascript como .contains ()
Usar el método .contains() podría ser un poco más seguro. No necesitará saber en qué parte de la URL 'pájaro'
se encuentra. Por ejemplo:
if (url.contains('bird')) {
// this is true
// do something
}
console.log(result);
// Check where the start (*) is in the string
var starIndex = str.indexOf('*');
a sta de st . de O ( );
// Check if each item contains an indexOf function, if it doesn't it's not a (standard) string.
// It doesn't necessarily mean it IS a string either.
if(!arr[i].indexOf) continue;
Hay una larga lista de advertencias para un método como este, y una larga lista de 'qué pasaría si' que no se
tienen en cuenta, algunas de las cuales se mencionan en otras respuestas. Pero para un uso simple de la sintaxis
de estrella, este puede ser un buen punto de partida.
Violín
0 James Hay 7 oct. 2014
The most convenient and reliable file
storage service
Receive your personal cloud storage with 2Gb of space for free
Content dated before 2011-04-08 (UTC) is licensed under CC BY-SA 2.5.Content dated from 2011-04-08 up to but not including 2018-05-02 (UTC) is licensed under CC BY-SA 3.0.Content dated on