Str_shuffle () equivalent in javascript?

As a function str_shuffle()in PHP, is there a function similar to line shuffling in javascript?

Please, help!

+3
source share
6 answers

There is no such function, you yourself will write it. Here is 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'));
+4
source

You can use the php.js implementation: http://phpjs.org/functions/str_shuffle∗29

+1
source

, String, .

0

php.js

function str_shuffle (str) {

    var newStr = [];

    if (arguments.length < 1) {
        throw 'str_shuffle : Parameter str not specified';
    }

    if (typeof str !== 'string') {
        throw 'str_shuffle : Parameter str ( = ' + str + ') is not a string';
    }

    str = str.split (''); 
    while (str.length) {
        newStr.push (str.splice (Math.floor (Math.random () * (str.length - 1)) , 1)[0]);
    }

    return newStr.join ('');
}
0

You can also do this as a prototype:

String.prototype.shuffle = function() {
  var parts = this.split('');

  for (var i = 0, len = parts.length; i < len; i++) {
    var j = Math.floor( Math.random() * ( i + 1 ) );
    var temp = parts[i];
    parts[i] = parts[j];
    parts[j] = temp;
  }

  return parts.join('');
};

Using it like this:

var myString = "Hello";
myString = myString.shuffle();
0
source

I would recommend lodash shuffle .

const result = _.shuffle('my_string');
0
source

Source: https://habr.com/ru/post/1750901/


All Articles