Skip to content

Instantly share code, notes, and snippets.

@Anthodpnt
Last active December 13, 2016 22:38
Show Gist options
  • Save Anthodpnt/947bfbbe2f6b9c753bc5d94e777905ef to your computer and use it in GitHub Desktop.
Save Anthodpnt/947bfbbe2f6b9c753bc5d94e777905ef to your computer and use it in GitHub Desktop.
Misc - Mixing Text
/**
* This gist is for Javascript beginners.
* @author: Anthony Du Pont <antho.dpnt@gmail.com>
* @site: https://www.twitter.com/JsGists
*
* A trendy effect to add to your websites is to mix some text to create a sort of glitch.
* They are many styles and ways to mix text and create this kind of effect but let me show
* you an easy solution to manipulate a string and mix it.
*
* Example:
* I have a string I want to mix without adding any other characters.
* I just want a simple and efficient way of mixing it.
**/
const text = 'Banana, Apple and Orange';
const mixed = mixText(text);
function mixText(string) {
// We split our string to create an array of characters.
// I choose to split any character but you could use a
// regex to split your text as you want (by word,...).
const array = string.split('');
// Then we need to create an empty array that will contain
// all the mixed characters from our string. We will use
// this array to output our mixed string.
const mix = [];
while (array.length > 0) {
// Get a random index from the initial array.
const index = Math.floor(Math.random() * array.length);
// Add random entry from array to the mix.
mix.push(array[index]);
// Remove the entry added to the mix from the initial array.
array.splice(index, 1);
}
return mix.join(''); // Return our mixed string.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment