You will see, I created an array that creates a random text that it places in a link, replacing the spaces with -
but it returns undefined.
This is my code:
var array = ["texto 1", "text 2", "text 3", "text 4"];
var random = Math.floor(Math.random() * array.length);
$('a').attr('href', array[random].replace(/\s/g, "-"));
Javascript arrays start at zero and have indices [0 ... length-1].
You are making a random that will sometimes point to index [length], which doesn't exist. (although this possibility is minuscule and I'm surprised it's always giving you undefined.
To make sure you never target index 4, you should do:
But this is not going to give you an equiprobable result. In this solution, the possibility of text 4 appearing is negligible.
I would fix it by looking at the edge case (random===array.length) and fixing it to point to the previous index:
PS: the name "array" is a very bad name for an array.