Snippet. JavaScript. Generate Random Character

This JavaScript snippet shows how to generate a random character. A randomly generated character may be necessary to generate random names, ids, etc.

Function random_character

The function random_character returns a randomly generated character. The returned characters may be in the ranges 0-10, a-z, A-Z. If you don't want some characters you may remove them at will.

function random_character() {
    var chars = "0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ";
    return chars.substr( Math.floor(Math.random() * 62), 1);
}

Example

var rchar = random_character();

alert("Your lucky character is " + rchar);

Test


Updated on: 23 Nov 2024