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

123
Visualizações
Randomize words in a sentence / string with Javascript and list all the variations

i've searched a lot but havent found exactly what i am trying to do. But here goes:

I want to input a sentence / string in javascript and output all randomized variations of that sentence.

Example input: 'my test sentence 123' output: 'test my sentence 123', 'my sentence 123 test', '123 sentence my test', and so on, and stop when theres no variations left.

I've split the sentence into words in an array, but im a bit stuck on how to proceed to randomize the words and join them to new sentences in a list or new array.

code so far:

    let str = "my test sentence 123";
    let words = str.split(" ");
    for (let i = 0; i < words.length - 1; i++) {
    words[i] += " ";
    }

A bit stuck on how to proceed. My thought process is: I have the words variable / array, but i need to randomize each word, output new strings but also check the existing ones so i don't duplicate any of them.

Thanks for all help i can get to learn more :)

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Check this code

    var phrase = "my test sentence 123";
    var words = phrase.toLowerCase().match(/\w+/g);
    var wordsCopy = phrase.toLowerCase().match(/\w+/g);

    // First of all I loop each word
    words.forEach(function(word, index){
        // Random word going to contain my randomized word
        var randomWord = word;
      
      // Copy the entire phrase
      var wordsMissing = wordsCopy.slice();
      
      // Remove the current word
      wordsMissing.splice(wordsCopy.indexOf(word), 1);
      
      // Loop tru my missing words
      for (var i = 0; i < wordsMissing.length; i++) {
        // Set my random word with the rest of the words
        randomWord += " " + wordsMissing.join(" ");
        
        // get the first word and send to the final of my original phrase
        var firstWord = wordsMissing.splice(0,1)[0];  
        wordsMissing.push(firstWord);
        
        // Log my random word
        console.log(randomWord);
        
        // Reset random word to the initial word
        randomWord = word;
      }
    });
about 4 years ago · Juan Pablo Isaza Relatório

0

As you are on Javascript, using .join(' ') will be easier to create a string from an array.

Then, there is a lot of solutions to achieve what you want to do, the easier way would be a foreach on foreach, where you simply test if the string you created already exists in the array.

It would be the easy way, but the more you put items, the more you will need power, so use this solution wisely.

Something like this can work :

var stringToSplit = 'I want to split this'

var stringSplitted = stringToSplit.split(' ')

var arrayOfNewStrings = []

stringSplitted.forEach(word => {
    var arrayOfString = []
    arrayOfString.push(word)
    stringSplitted.forEach(otherWord => {
        if(word !== otherWord)
        arrayOfString.push(otherWord)
    })
    arrayOfNewStrings.push(arrayOfString)
});

console.log(arrayOfNewStrings)

You then need to add a layer of for/foreach to make it for every words (this will work only for the first one), and to test if the array already exists in ArrayOfNewStrings to prevent duplication.

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