Home > Back-end >  Javascript: Shuffle per word only
Javascript: Shuffle per word only

Time:01-18

Please see my code below. When it shuffles it also shuffles the space. I want to shuffle it per word.

For example

  • eHllo rWold
  • Hlloe woRld

but when i shuffle the space is everywhere and also the strings. Please see below:

  • olHlwod lre
  • Hdre olllwo

Thank you

<!DOCTYPE html>
<html>
<head>
<style>
  * { font-family: Calibri; }
  p, input {font-size: 18px; }
</style>
</head>

<body>
  <h2>
    Click button to shuffle characters of the below string
  </h2>
  <p>
  </p>
  
  <p>
    <input type='button' value='Click to shuffle' id='bt' onclick='shuffle("Hello world")' />
  </p>
  
  <p id='result'></p>
</body>

<script>
  let shuffle = (s) => {
    
    let arr = s.split(''), arr_len = arr.length;
    
    while (arr_len) {
      let rnd = Math.floor(Math.random() * arr_len--);
      [arr[arr_len], arr[rnd]] = [arr[rnd] , arr[arr_len]];
    }
    
    let str = arr.join('');
    
    // show shuffled characters.
    document.getElementById('result').innerHTML = str;
  }
</script>
</html>

CodePudding user response:

You can split on whitespace and shuffle each part separately.

let shuffle = (s) => {
  let arr = [...s], arr_len = arr.length;
  while (arr_len) {
    let rnd = Math.floor(Math.random() * arr_len--);
    [arr[arr_len], arr[rnd]] = [arr[rnd], arr[arr_len]];
  }
  return arr.join('');
}
document.getElementById('bt').addEventListener('click', e => {
  let text = "Hello world";
  let res = text.split(/\s /).map(shuffle).join(' ');
  document.getElementById('result').textContent = res;
});
<h2>Click button to shuffle characters of the below string</h2>
<p><input type='button' value='Click to shuffle' id='bt'/></p>
<p id='result'></p>

CodePudding user response:

You will first have to split your string, then shuffle the individual components and combine them back into a string again. Here is a simple example:

const shuffle = (s) => {
    
    let arr = s.split(''), arr_len = arr.length;
    
    while (arr_len) {
      let rnd = Math.floor(Math.random() * arr_len--);
      [arr[arr_len], arr[rnd]] = [arr[rnd] , arr[arr_len]];
    }
     
    // Let's return it here so we can use shuffle() anywhere to shuffle any string
    // The output is for some other method to hook up.
    
    return arr.join('');
    
 }

const input = document.querySelector( '#input' ) 
const output = document.querySelector( '#output' );

input.addEventListener( 'input', event => {
    
    output.innerText = input.value.split( ' ' ).map( shuffle ).join( ' ' );
  
});
<input type="text" id="input" />
<div id="output"></div>

CodePudding user response:

It looks like you are missing the space in the split. Try this:

let arr = s.split(' ')

CodePudding user response:

function shuffle(str = '') {
  const words = str.split(' ');
  const result = [];
  words.forEach(word => {
    word = word.split('');
    const shuffleWord = word.sort(() => Math.random() - 0.5);
    result.push(shuffleWord.join(''));
  })
  return result.join(' ');
}

alert(shuffle('Hello World'));

CodePudding user response:

Can you try this :

I used forEach to split the string into two then apply the shuffle

  let shuffle = (s) => {
    let strings = s.split(' ');
    let str = '';
    strings.forEach((element) => {
      let arr = element.split('');
      let arr_len = arr.length;
    
      while (arr_len) {
        let rnd = Math.floor(Math.random() * arr_len--);
        [arr[arr_len], arr[rnd]] = [arr[rnd] , arr[arr_len]];
      }
   
       str  = arr.join('');
       str  = ' ';
    });
    

    // show shuffled characters.
    document.getElementById('result').innerHTML = str;
  }
<!DOCTYPE html>
<html>
<head>
<style>
  * { font-family: Calibri; }
  p, input {font-size: 18px; }
</style>
</head>

<body>
  <h2>
    Click button to shuffle characters of the below string
  </h2>
  <p>
  </p>
  
  <p>
    <input type='button' value='Click to shuffle' id='bt' onclick='shuffle("Hello world")' />
  </p>
  
  <p id='result'></p>
</body>


</html>

  • Related