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
You can split on whitespace and shuffle each part separately.
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:
It looks like you are missing the space in the split. Try this:
One line solution:
Or with the help of
reduce()
:Can you try this :
I used
forEach
to split the string into two then apply the shuffle