javascript - I would like to know how to sort just letters that are in a function



How do I use pure javascript to sort a group of letters like I've written below. Do you I use a .match [a-zA-Z]? or split? Or something else ?? For instance:

   // Result should be something like: BLL5*RnEM*nX8x@3
   // Only the letters should be randomly sorted

this is what I have so far. It keeps on spitting out random letters without numbers like "RnEMBLLxnX@"

 function randomsort(a, b) { 
return Math.random()>.5 ? -1 : 1;
 var arrStr = 'x5*RnEM*BLL8nX@3';
 var res = arrStr.split(/[0-9]/gi).sort(randomsort,/[0-9]/gi); 
var randomStr = arrStr.split(/[0-9]/gi).sort(randomsort,/[0-9]/gi); 
 console.log(randomStr.join('')); // returns something like *RnEM*BLLxnX@" 

I also created a function that keeps the numbers and symbols and replaces the letters with the first letter in the string (x5*xxxx*xxx8xx@3).

 function myFunction() {
  var arrStr = "x5*RnEM*BLL8nX@3"; 
  var letters = arrStr.split(/[0-9]/gi).sort(randomsort,/[0-9]/gi); 

  var res = arrStr.replace(/[a-z]/gi, letters[0]);

 document.getElementById("demo").innerHTML = res  //displays something like x5*xxxx*xxx8xx@3

1 Answer: 

I'm sure there's other (better) ways to do this, but here's a solution.

First you separate letter groups and non letter groups into two different arrays. You then shuffle the letter groups in whatever way you feel like. Then you recombine the shuffled letter groups array with your other array.

In the example below I use String#match to create the two arrays, shuffle one, and then Array#map and Array#join to put the entire thing back together.

let str = 'x5*RnEM*BLL8nX@3'

// Get an array of letter groups
let a = str.match(/[a-z]+/gi)
// Get array of everything else in the string
let b = str.match(/[^a-z]+/gi)

// Shuffle the letter groups randomly
var j, x, i;
for (i = a.length - 1; i > 0; i--) {
    j = Math.floor(Math.random() * (i + 1));
    x = a[i];
    a[i] = a[j];
    a[j] = x;

// Recombine the two arrays
let newstr =,i)=>{return s + (b[i] || "")}).join("")