Está en la página 1de 10

/home/español/javascript/Comparación de cadenas comodín en Javascript

Comparación de cadenas comodín en Javascript


it-swarm.dev 🔍
Digamos que tengo una matriz con muchas cadenas llamadas "birdBlue" , "birdRed" y algunos otros animales como
"pig1" , "pig2" ).

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?

javascript string comparison

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"

"* b" => todo lo que termina con "b"


"* a *" => todo lo que tiene una "a"
"* a * b *" => todo lo que tiene una "a", seguida de cualquier cosa, seguida de una "b", seguida de
cualquier cosa

o en tu ejemplo: "pájaro *" => todo lo que comienza con pájaro

Tuve un problema similar y escribí una función con RegExp:

//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");

// "." => Find a single character, except newline or line terminator


// ".*" => Matches any string that contains zero or more characters
rule = rule.split("*").map(escapeRegex).join(".*");

// "^" => 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);

//Returns true if it finds a match, otherwise it returns false


return regex.test(str);

//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"
);

Si desea leer más sobre las funciones utilizadas:

RegExp "^,., *, $"


cadena dividida ("*")
combinación de matriz (". *")
nuevo RegExp (patrón [ banderas])
RegExpObject.test (string)

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

10 Davsket 7 oct. 2014

Puede usar el método Javascript subcadena . Por ejemplo:

var list = ["bird1", "bird2", "pig1"]

for (var i = 0; i < list.length; i++) {


if (list[i].substring(0,4) == "bird") {
console.log(list[i]);
}
}

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",
]

for (var i = 0; i < list.length; i++) {


if (listOfUrls[i].substring(0,4) === 'bird') {
// do something
}
}

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:

var url = 'www.example.com/bird?=fly'

if (url.contains('bird')) {
// this is true
// do something
}

2 Cody Reichert 7 oct. 2014


 
Aquí hay un fragmento con soporte para comodines * y ?

let arr = ["birdBlue", "birdRed", "pig1", "pig2" ];


let wild = 'bird*';

let re = new RegExp('^'+wild.replace(/\*/g,'.*').replace(/\?/g,'.')+'$');


let result = arr.filter( x => re.test(x.toLowerCase()) );

console.log(result);

0 Kamil Kiełczewski 16 ago. 2019

var searchArray = function(arr, str){


// If there are no items in the array, return an empty array
if(typeof arr === 'undefined' || arr.length === 0) return [];
// If the string is empty return all items in the array
if(typeof str === 'undefined' || str.length === 0) return arr;

// Create a new array to hold the results.


var res = [];

 
// Check where the start (*) is in the string
var starIndex = str.indexOf('*');
a sta de st . de O ( );

// If the star is the first character...


if(starIndex === 0) {

// Get the string without the star.


str = str.substr(1);
for(var i = 0; i < arr.length; i++) {

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

// Check if the string is at the end of each item.


if(arr[i].indexOf(str) === arr[i].length - str.length) {
// If it is, add the item to the results.
res.Push(arr[i]);
}
}
}
// Otherwise, if the star is the last character
else if(starIndex === str.length - 1) {
// Get the string without the star.
str = str.substr(0, str.length - 1);
for(var i = 0; i < arr.length; i++){
// Check indexOf function
if(!arr[i].indexOf) continue;
// Check if the string is at the beginning of each item
if(arr[i].indexOf(str) === 0) {
// If it is, add the item to the results.
res.Push(arr[i]);
}
}  
}
// In any other case...
else {
for(var i = 0; i < arr.length; i++){
// Check indexOf function
if(!arr[i].indexOf) continue;
// Check if the string is anywhere in each item
if(arr[i].indexOf(str) !== -1) {
// If it is, add the item to the results
res.Push(arr[i]);
}
}
}

// Return the results as a new array.


return res;
}

var birds = ['bird1','somebird','bird5','bird-big','abird-song'];

var res = searchArray(birds, 'bird*');


// Results: bird1, bird5, bird-big
var res = searchArray(birds, '*bird');
// Results: somebird
var res = searchArray(birds, 'bird');
// Results: bird1, somebird, bird5, bird-big, abird-song

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

¿Una forma óptima de comparar cadenas en JavaScript?

La cadena JQuery contiene cheque

Comparar cadenas JavaScript Devolución% de probable

¿Cómo comprobar si una cadena contiene una subcadena en JavaScript?

¿Convertir una cadena en un entero?

Convertir un objeto en una cadena

Recortar cadena en JavaScript?

¿Cuándo usar comillas dobles o simples en JavaScript?


 
Obteniendo fecha y hora actual en JavaScript
¿Cómo encontrar si una matriz contiene una cadena específica en JavaScript/jQuery?

¿Convertir cadena de JavaScript a minúsculas?

¿Cómo puedo eliminar un carácter de una cadena usando Javascript?

JavaScript - Reemplace todas las comas en una cadena

Cómo eliminar todos los saltos de línea de una cadena

Eliminar HTML de texto JavaScript

¿Cómo saber si una cadena contiene un determinado carácter en JavaScript?

Cómo reemplazar todos los puntos en una cadena usando JavaScript

¿Cómo reemplazo un carácter en un índice particular en JavaScript?

Extraer ("obtener") un número de una cadena

¿Cómo se invierte una cadena en JavaScript?

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

or after 2018-05-02 (UTC) is licensed under CC BY-SA 4.0. | Privacy

También podría gustarte