PHP's str_shuffle in JavaScript

Here’s what our current JavaScript equivalent to PHP's str_shuffle looks like.

module.exports = function str_shuffle (str) { // eslint-disable-line camelcase
// discuss at:
// original by: Brett Zamir (
// example 1: var $shuffled = str_shuffle("abcdef")
// example 1: var $result = $shuffled.length
// returns 1: 6
if (arguments.length === 0) {
throw new Error('Wrong parameter count for str_shuffle()')
if (str === null) {
return ''
str += ''
let newStr = ''
let rand
let i = str.length
while (i) {
rand = Math.floor(Math.random() * i)
newStr += str.charAt(rand)
str = str.substring(0, rand) + str.substr(rand + 1)
return newStr

How to use

You you can install via npm install locutus and require it via require('locutus/php/strings/str_shuffle'). You could also require the strings module in full so that you could access strings.str_shuffle instead.


A community effort





#codeexpected result
1var $shuffled = str_shuffle("abcdef") var $result = $shuffled.length6

« More PHP strings functions