Reputation: 583
function scramble(a){a=a.split("");for(var b=a.length-1;0<b;b--){var c=Math.floor(Math.random()*(b+1));d=a[b];a[b]=a[c];a[c]=d}return a.join("")}
I've got this code, which seems to be effective in scrambling a single word by calling an alert:
alert(scramble('Like this.'));
Here's what I'm trying to do though: I want to be able to enter text in a textarea, separated by newlines, and randomly scramble each string line by line. For example:
testing
scramble
words
Would output something like:
sgnitte
rceamslb
dwros
Can anyone help me in doing this?
Upvotes: 3
Views: 8774
Reputation: 885
function Scamble (s,shift){
var r = "";
for(var i = 0; i < s.length; i++){
r += String.fromCharCode(s.charCodeAt(i) + shift)
}
return r
}
alert(Scamble ("abcd",33324)) //returns '芍芎芏芐'
alert(Scamble ('芍芎芏芐',-33324)) //returns abcd
Upvotes: 1
Reputation: 795
Try this code:
function scramble(a){a=a.split("");for(var b=a.length-1;0<b;b--){var c=Math.floor(Math.random()*(b+1));d=a[b];a[b]=a[c];a[c]=d}return a.join("")}
function scrambleText(){
var textArea = document.getElementById('TEXTAREA_ID');
var lines = textArea.value.split('\n');
for(var i = 0;i < lines.length;i++){
lines[i] = scramble(lines[i]).toUpperCase().split('').join(' ');
}
textArea.value = lines.join('\n');
}
First you get the text area element, then you get its value and split that into an array by line. You can then scramble each line individually with your existing function. Lastly, all there is to do is to convert the array back to a string and get the scrambled text back into the text area.
EDIT: You can use the toUpperCase
method to transform all characters to upper case. The combination of split
join
, like you can see in the code above, can be used to add spaces between the characters.
JSFiddle: https://jsfiddle.net/NotABlueWhale/u8wjuz1r/7/
Upvotes: 2
Reputation: 41893
function shuffle(str) {
var str = document.getElementById('txt');
var a = str.innerHTML;
var newArr = [];
var neww = '';
var text = a.replace(/[\r\n]/g, '').split(' ');
text.map(function(v) {
v.split('').map(function() {
var hash = Math.floor(Math.random() * v.length);
neww += v[hash];
v = v.replace(v.charAt(hash), '');
});
newArr.push(neww);
neww = '';
});
var x = newArr.map(v => v.split('').join(' ')).join('\n');
str.value = x.split('').map(v => v.toUpperCase()).join('');
}
<textarea cols='60' rows='8' id="txt">testing scramble words</textarea>
<button onclick='shuffle()'>Shuffle</button>
Upvotes: 4