Shuffle Characters of a String with JavaScript

12/21/2021

Contents

In this article, you will learn how to shuffle characters of a string with JavaScript.

Get the element

Create a p element in your document and have some text to shuffle. The querySelector is used to get the element.

HTML

<p class="str">Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>

JavaScript

const str = document.querySelector('.str');

Get the text of an element

Get the text that the specified element has. Use textContent to get the text.

HTML

<p class="str">Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>

JavaScript

const str = document.querySelector('.str');
const text = str.textContent;

Divide the text character by character into an array

Create an array by splitting the text character by character with split().
split () is a method that divides a character string at an arbitrary position into an array, and you can specify the split position of the character string as an argument.

HTML

<p class="str">Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>

JavaScript

const str = document.querySelector('.str');
const strArray = str.textContent.split('');

Shuffle the array and convert it to a string

Shuffle the array created by dividing the character string into characters one by one with sort (), and convert it to a character string with join().
The expression running in sort () is generating a random number.

HTML

<p class="str">Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>

JavaScript

const str = document.querySelector('.str');
const strArray = str.textContent.split('');

str.textContent = strArray.sort(function(){
    return Math.random() - 0.5;
}).join('');