skip to Main Content

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>

5

Answers


  1. 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>
    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
  3. It looks like you are missing the space in the split. Try this:

    let arr = s.split(' ')
    
    Login or Signup to reply.
  4. One line solution:

    alert( 'Hello World'.split(' ').map( word => word.split('').sort( () => Math.random() - 0.5 ).join('') ).join(' ') );

    Or with the help of reduce():

    function shuffle(str = '') {
      const words = str.split(' ');
      const result = words.reduce((prev, current) => {
        current = current.split('');
        current = current.sort(() => Math.random() - 0.5);
        prev.push(current.join(''));
        return prev;
      }, [])
      return result.join(' ');
    }
    
    alert( shuffle('Hello World') );
    Login or Signup to reply.
  5. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search