Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a JavaScript string/word scrambler

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?

like image 881
Craig Avatar asked Apr 24 '26 13:04

Craig


2 Answers

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 &#13;&#10;scramble &#13;&#10;words</textarea>
<button onclick='shuffle()'>Shuffle</button>
like image 174
kind user Avatar answered Apr 27 '26 02:04

kind user


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/

like image 26
NotABlueWhale Avatar answered Apr 27 '26 03:04

NotABlueWhale



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!