Built From Developers For Developers
» Kuikie.com » Snippets » JavaScript » Strings » JavaScript. Generate Random String
  Categories
  JavaScript
    Ajax
    IFrame
    Integers
    Other
    Strings
 

JavaScript. Generate Random String

This JavaScript snippet shows how to generate a random string. A randomly generated string is necessary in many occasions. For instance, to open popup windows, assign unique ID to page elements, generate random passwords, etc.

Function random_string

The function random_string returns a randomly generated string. The string accepts one argument, which specified the length of the returned string. The returned string will be composed of characters in the ranges 0-10, a-z, A-Z. The function uses another helper function called random_character to generate the random string.

function random_string(size){
    var str = "";
    for (var i = 0; i < size; i++){
        str += random_character();
    }
    return str;
}
function random_character() {
    var chars = "0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ";
    return chars.substr( Math.floor(Math.random() * 62), 1);
}

Example

var rstr = random_string(12);

alert("Your lucky string is " + rstr);

Test




 
©2012 Sinevia Ltd Terms of Use         Privacy Policy Valid XHTML 1.0 Transitional