Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

479
Visualizações
How do i replace vowel(s) from a character with * and get an array of all the possiblities in js

Suppose that i have a word "FadTheChad" (or any word that has vowels) and want the vowels replaced with "*" and return all the possibilities (subsets? not sure how i could describe it) of the word in an array.

I tried using String.replace() on the whole string which gave me F*dTh*Ch*d. Then i tried looping over the string and doing .replace() again which returned F*dTheChad, FadTh*Chad, FadTheCh*d.

is there anyway that i could get something like

[
  'F*dTh*Ch*d',
  'F*dTheChad',
  'F*dTh*Chad',
  'F*dTheCh*d',
  'FadTh*Chad',
  'FadTh*Ch*d',
  'FadTheCh*d'
]
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Try this:

function getPossibilities(word) {
    let vowels = ['a', 'e', 'i', 'o', 'u']; // 'y'?
    let positions = [];
    for (let i = 0; i < word.length; i++) {
        if (vowels.indexOf(word[i]) !== -1) positions.push(i);
    }
    let result = [], count = 2 ** positions.length;
    for (let i = 0; i < count; i++) {
        let newWord = [...word];
        for (let j = 0; j < positions.length; j++) {
            if ((i >> j) & 1) newWord[positions[j]] = '*';
        }
        result.push(newWord.join(''));
    }
    return result;
}

I make the word into an array because in JS strings are immutable so I wouldn't be able to modify indices like this.

about 4 years ago · Juan Pablo Isaza Relatório

0

Updated Answer

Ok, now that I understand the question before answering it (see original below for explanation), this can also be answered with a simple recursion:

const addAsterisks = ([c,...cs]) =>
  c == undefined
    ? ['']
    : addAsterisks (cs) .flatMap (
        (w) => 'aeiou' .includes (c) ? [c + w, '*' + w] : [c + w]
      )

console .log (addAsterisks ('FadTheChad'))
.as-console-wrapper {max-height: 100% !important; top: 0}

If the string is empty, we return an array containing the empty string. Otherwise we recur on the remainder of the string, and for each result, we return an array with the our current character prepended to the result and, if the current character is a vowel, an asterisk prepended to the result.

Original Answer

(This answered a different question altogether, based on my misreading. It's still interesting in its own right.)

A simple recursion makes this easy:

const addVowels = (str) => 
  str .indexOf ('*') < 0 
    ? str 
    : ['a', 'e', 'i', 'o', 'u'] .flatMap (v => addVowels (str .replace ('*', v)))

console .log (addVowels ('F*dTh*Ch*d'))
.as-console-wrapper {max-height: 100% !important; top: 0}

If our string contains no asterisks, we are done and simply return it.

If it has an asterisk, flatMapping the results of replacing that with each of the vowels and recurring on the resulting string.


For next time, please include some sample code for what you've tried.

about 4 years ago · Juan Pablo Isaza Relatório

0

So the question is to find the vowels, then to find all possible combinations by replacing them with star.. pretty nice so here's my attempt

function vowelOptions(text,replacer){
  let isVowel={a:1,e:1,i:1,o:1,u:1}
  let vowels=[], toReturn=[]
  let data=text.split('')
  data.forEach((letter,i)=>{
    if(isVowel[letter]){vowels.push(i)} //location of vowel stored
  })
  for(let i=1;i<Math.pow(2,vowels.length);i++){
    //Math.pow(2,vowels.length) are the number of vowel possibilities
    //i=1 and NOT 0 because default text is now allowed in return
    let dataOption=[...data] //a clone with a possible combination
    let combination=i.toString(2).split('').reverse() //the ones that will be '1' tell me where to put the replacer
    combination.forEach((bool,j)=>{
      if(bool=='1'){dataOption[vowels[j]]=replacer} //vowels to replace in this combination replaced thanks to vowel locations saved above
    })
    toReturn.push(dataOption.join(''))
  }
  return toReturn
}

//now watch it work >:}
console.log(vowelOptions("FadTheChad","*"))

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda