Quiero encontrar una palabra por la posición de sus caracteres:
const wordlist = ['xenon', 'rewax', 'roger', 'bob', 'xylophone'] Y, para encontrar xilófono, tendré:
const charSlotPairs = [{char: "x", slot: 0}, {char: "y", slot: 1}];
así que estoy creando dinámicamente la expresión regular (^.{0}[x])(^.{1}[y]) pero creo que esta expresión regular es incorrecta... ¿Cómo encuentro coincidencias en función de la posición de un carácter? en una cadena?
function (charSlotPairs){ let regexStr = "" charSlotPairs.forEach( pair => { regexStr += `(^.{${pair.slot}}[${pair.char}])` }) const regex = new RegExp(`${regexStr}\\w`, 'g') return this.filter( word => !word.match(regex) ) }Esta es la forma en que lo resolvería en lugar de usar expresiones regulares:
function (charSlotPairs){ return !!charSlotPairs.find(pair => a.every( word => word.charAt(pair.slot) == pair.char) ) }Su consulta se puede resolver solo con el uso de bucle.
const wordlist = ['xenon', 'rewax', 'roger', 'bob', 'xylophone']; const charSlotPairs = [{char: "x", slot: 0}, {char: "y", slot: 1}]; let stringFinder = (StrArr, KeyArr) => { var match = false; // Indicator Variable // For Iterating a String Array for (var i of StrArr) { // For Iterating the Object Array for each Key for (var x of KeyArr) { /* |If Conditon fails, match will set to false and Loop will Break |Otherwise Loop will continue */ if (i.charAt(x.slot) != x.char) { match = false; break; } else { match = true; } } /* |If the Inner Loop is completed and match is true => Success |If the Inner Loop is completed and match is false => Failed */ if (match) { return i; } } return false; } console.log(stringFinder(wordlist, charSlotPairs));Terminé filtrando la lista de palabras y luego usando .every() para asegurarme de que todas pasaran el filtro.
Array.prototype.findWordsWithLettersInSlots = function (letterSlotPairs){ if( letterSlotPairs.length === 0 ) return this if( Object.keys(letterSlotPairs).length === 0 ) return this return this.filter( word => { return letterSlotPairs.every( (pair) => { return word.charAt(pair.slot) === pair.letter }) }) }