I’m a javascript beginner and I got stuck having a problem. I have a javascript’s function to shuffle the characters in a string in that way that words length and spaces are kept like in original sentence.
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
String.prototype.shuffle = function () {
// pass to shuffleArray an array of all non-whitespace characters:
const randomChars = shuffleArray([...this.replace(/s+/g, '')]);
let index = 0;
// `S` matches any non-whitespace character:
return this.replace(/S/g, () => randomChars[index++]);
}
console.log(
`The keys are under the mat`
.shuffle()
);
What I want to add is adding to the function a variable with defined letters which should be skipping in shuffle process. Now we have, i.e:
- original string:
The keys are under the mat
- now shuffled string looks like:
atd meey eke nTshr hau ert
- and what I want:
I want to define characters e.g: [hr] and those letters should stay "frozen" in their positions and not be processed by shuffle function:
final result:
ahd meey ere nTshr ahu ekt
3
Answers
The best solution I can come up with is the following:
There’s a lot of ways to go about this, but making it efficient depends on a bunch of factors, such as the specific input string, it’s length and the number of characters in your exclusion array.
I’d look into using the .split() method, demonstrated here: w3schools .split()
Hope this helps.
You could take a string of characters who remain and build two regular expression for collection and replacing.
I believe this code does what you are looking for:
It is O(n), n being the number of letters in the text.
Hope it helps!