How to Shuffle the Characters in a String in JavaScript

How do I shuffle the characters in a string in JavaScript?

I modified an example from the Fisher-Yates Shuffle entry on Wikipedia to shuffle strings:

String.prototype.shuffle = function () {
var a = this.split(""),
n = a.length;

for(var i = n - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
return a.join("");
}
console.log("the quick brown fox jumps over the lazy dog".shuffle());
//-> "veolrm hth ke opynug tusbxq ocrad ofeizwj"

console.log("the quick brown fox jumps over the lazy dog".shuffle());
//-> "o dt hutpe u iqrxj yaenbwoolhsvmkcger ozf "

More information can be found in Jon Skeet's answer to Is it correct to use JavaScript Array.sort() method for shuffling?.

How to shuffle middle letters in between specific indexes of a word?

This should work well

<template>
<div>
<p>
The idea is to have a string, with it's first 2 indexes and last one
untouched while all the others indexes are shuffled
</p>
<pre>combination found for string '{{ baseWord }}'</pre>
<pre>actual list: {{ results }}</pre>
</div>
</template>

<script>
const shuffledMiddleLetters = (array) =>
array
.split('')
.sort(() => 0.5 - Math.random())
.join('')

const wordMiddlePart = (word) => word.slice(2, word.length - 1)

export default {
data() {
return {
baseWord: 'watermelon',
results: [],
}
},
mounted() {
const shuffledMiddleLettersVariants = [...Array(50)].map(() =>
shuffledMiddleLetters(wordMiddlePart(this.baseWord))
)

const dedupedVariants = [
...new Set([
wordMiddlePart(this.baseWord),
...shuffledMiddleLettersVariants,
]),
]
this.results = dedupedVariants.map((dedupedVariants) =>
[
this.baseWord.slice(0, 2),
dedupedVariants,
this.baseWord[this.baseWord.length - 1],
].join('')
)
},
}
</script>

This is how it looks

Sample Image

Randomize each characters casing in a string

Build a new string with adding char for char in randomly upper-/lowercase to it.

var message = 'This message is for testing'
let result ="";
for (var i = 0; i < message.length; i++) {
var random_number = Math.round(Math.random() * 10 + 1);
if(random_number % 2 == 0) {
result += message.charAt(i).toUpperCase();
} else {
result += message.charAt(i);
}
}
console.log(result)

str_shuffle() equivalent in javascript?

No such function exist, you'll write one yourself. Here's an example:

function shuffle(string) {
var parts = string.split('');
for (var i = parts.length; i > 0;) {
var random = parseInt(Math.random() * i);
var temp = parts[--i];
parts[i] = parts[random];
parts[random] = temp;
}
return parts.join('');
}

alert(shuffle('abcdef'));

How do I pick random characters from a string?

You can shuffle and pick top 4 (or last 4) characters

var shuffled = (str) => str.split('').sort(function() {  return 0.5 - Math.random();}).join('');var letters = "ABCDEFGHIJK";
console.log(shuffled(letters).slice(-4)); //last 4
console.log(shuffled(letters).slice(-4)); //last 4 console.log(shuffled(letters).substring(0,4)); //top 4

JS: Array shuffling, not string shuffling

Your shuffle is a bit off, I looked at this which uses an array to shuffle.

// String concatenation
tp = rl + rn + rs;
tp=tp.split('');

// Shuffling part
for(var i = 0; i < tp.length; i++) {
var rnd = Math.floor(Math.random() * tp.length);
var temp = tp[i];
tp[i] = tp[rnd];
tp[rnd] = temp;
}
tp=tp.join("");

Shuffling a string with a seed

Array-style access to individual characters in JavaScript strings is read only. (And not supported at all in older browsers.)

A minimal change to your code to get it to work would be to convert your string to an array for processing and then convert it back to a string when you return it:

function shufff(strin,seed){
strin = strin.split("");
var tem;
var j;
var tt = strin.length;
for(var i=0; i<tt; i++){
j = ( seed % (i+1) + i) % tt;
tem=strin[i];
strin[i] = strin[j];
strin[j] = tem;
}
return strin.join("");
}

Working demo: http://jsfiddle.net/fcKDN/



Related Topics



Leave a reply



Submit