Pick random word javascript

This script should pick a random word from the available characters and add it add the end of the url but it doesn’t seems to work. Can you identify where I am making the problem??

    <script type="text/javascript">
    function randomEI1(len) {
var chars = [ "apple", "google", "ebay" ];
 var string_length = len;
 var randomstring ='';
        var rnum = Math.floor(Math.random() * chars.length);
        randomstring += chars.substring(rnum, rnum + 1);
    }
    return randomstring;
}

var ei1 = randomEI1(1);

document.write('<script type="text/javascript" src="http://www.site.com' + ei1 + '"></script>');

</script>

asked Sep 23, 2013 at 16:06

user2807931's user avatar

3

function randomEI1() {
   var chars = [ "apple", "google", "ebay" ];
   return chars[ Math.floor(Math.random() * chars.length)];
}
var ei1 = randomEI1();
document.write('<script type="text/javascript" src="http://www.site.com' + ei1 + '"> </script>');

I’m not sure what you were doing with the len parameter. Does this suit your needs?

answered Sep 23, 2013 at 16:26

Daniel Jones's user avatar

1

// DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE // Version 2, December 2004 // // Copyright (C) 2015 Swen Wenzel <swenzel@uos.de> // // Everyone is permitted to copy and distribute verbatim or modified // copies of this license document, and changing it is allowed as long // as the name is changed. // // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION // // 0. You just DO WHAT THE FUCK YOU WANT TO. // This generator yields everything from ~2% real english words over ~75% english sounding words and ~10% strange words to ~13% unreadable crap. // Try it out. It was created as a tradeoff between size and good results, if you need something better, well do it yourself. // If you drop me a line I might also be able to dig out the initial python source for this thing which was more powerful and worked // with more than just 1grams and 10 followers. // If you think you have an improvement, write a comment. // list of characters with their followers’ corresponding accumulated propabilities // accumulated probabilities are usable as keys and work great with Math.random() var grams = { » «: {0.6294: «s», 1.0: «t», 0.5166: «i», 0.2635: «c», 0.1255: «h», 0.7882: «a», 0.4297: «w», 0.1915: «b», 0.3464: «o», 0.0603: «f»}, «a»: {1.0: «n», 0.507: «l», 0.1379: «i», 0.3973: » «, 0.0446: «y», 0.6368: «r», 0.1865: «c», 0.0895: «m», 0.2906: «s», 0.7853: «t»}, «c»: {1.0: «o», 0.078: «r», 0.7882: «h», 0.3303: «t», 0.6334: «e», 0.181: «i», 0.0365: » «, 0.4808: «a», 0.2455: «k», 0.1214: «l»}, «b»: {1.0: «e», 0.0168: «s», 0.5666: «o», 0.3311: «l», 0.7064: «a», 0.042: » «, 0.2285: «i», 0.1634: «r», 0.1023: «y», 0.445: «u»}, «e»: {1.0: » «, 0.3763: «s», 0.2035: «a», 0.2859: «d», 0.0326: «c», 0.6218: «r», 0.1016: «e», 0.0666: «t», 0.14: «l», 0.4732: «n»}, «d»: {0.4397: «e», 1.0: » «, 0.0217: «d», 0.0671: «u», 0.044: «r», 0.0109: «y», 0.2946: «i», 0.0974: «s», 0.1495: «a», 0.2076: «o»}, «g»: {0.4683: «h», 1.0: » «, 0.0461: «s», 0.3648: «o», 0.0214: «n», 0.1991: «r», 0.2811: «a», 0.0805: «u», 0.1315: «i», 0.6221: «e»}, «f»: {0.1547: «a», 1.0: » «, 0.0923: «t», 0.0555: «u», 0.3867: «e», 0.2186: «f», 0.2981: «r», 0.0235: «l», 0.5046: «i», 0.7035: «o»}, «i»: {0.125: «e», 1.0: «n», 0.5324: «s», 0.1826: «d», 0.4017: «c», 0.3255: «o», 0.6677: «t», 0.2528: «l», 0.0382: «g», 0.081: «r»}, «h»: {0.0636: «t», 1.0: «e», 0.0099: «y», 0.3911: «i», 0.0382: «r», 0.0043: «n», 0.1563: «o», 0.2699: » «, 0.0219: «u», 0.5663: «a»}, «k»: {1.0: «e», 0.0184: «y», 0.2099: «s», 0.0336: «o», 0.1346: «n», 0.0828: «a», 0.664: » «, 0.0066: «u», 0.0526: «l», 0.3508: «i»}, «j»: {0.3455: «a», 1.0: «u», 0.0009: «s», 0.0314: » «, 0.2002: «e», 0.0618: «i», 0.0051: «p», 0.0021: «c», 0.6376: «o», 0.0132: «r»}, «m»: {1.0: «e», 0.7376: «a», 0.0544: «b», 0.2917: «i», 0.1154: «u», 0.4078: «o», 0.0265: «s», 0.1847: «p», 0.5582: » «, 0.0833: «m»}, «l»: {1.0: » «, 0.8256: «e», 0.0557: «s», 0.5064: «i», 0.2714: «o», 0.0221: «u», 0.1913: «y», 0.6551: «l», 0.3799: «a», 0.1173: «d»}, «o»: {0.4793: «u», 1.0: «n», 0.8009: » «, 0.0373: «o», 0.3502: «f», 0.1282: «w», 0.0817: «l», 0.1832: «t», 0.6375: «r», 0.2536: «m»}, «n»: {1.0: » «, 0.5597: «g», 0.4228: «t», 0.1167: «i», 0.3088: «e», 0.7117: «d», 0.2199: «s», 0.0764: «c», 0.0377: «a», 0.1673: «o»}, «q»: {1.0: «u», 0.0059: «l», 0.0136: «b», 0.0017: «s», 0.0348: «i», 0.0218: «a», 0.003: «w», 0.0043: «w», 0.0006: «v», 0.0888: » «}, «p»: {1.0: «e», 0.18: «i», 0.5315: «a», 0.4013: «l», 0.8133: «r», 0.124: «p», 0.2815: » «, 0.0687: «u», 0.6631: «o», 0.0274: «t»}, «s»: {1.0: » «, 0.2935: «i», 0.1824: «a», 0.3978: «e», 0.5411: «t», 0.0947: «s», 0.1379: «h», 0.053: «u», 0.0224: «p», 0.2328: «o»}, «r»: {1.0: «e», 0.1439: «t», 0.0554: «d», 0.2183: «s», 0.0245: «n», 0.5049: «o», 0.7461: » «, 0.0896: «y», 0.4002: «i», 0.3042: «a»}, «u»: {1.0: «r», 0.5156: «s», 0.2004: » «, 0.3647: «l», 0.259: «p», 0.1475: «c», 0.6674: «n», 0.0476: «e», 0.8267: «t», 0.0963: «g»}, «t»: {0.1525: «a», 0.0368: «u», 1.0: «h», 0.1056: «r», 0.4593: «o», 0.071: «s», 0.3457: «e», 0.7133: » «, 0.0183: «t», 0.243: «i»}, «w»: {0.0373: «s», 0.0059: «l», 0.8036: «a», 1.0: «i», 0.6122: «e», 0.3096: «o», 0.1913: » «, 0.0183: «r», 0.4543: «h», 0.0822: «n»}, «v»: {1.0: «e», 0.007: «s», 0.0014: «d», 0.0737: «o», 0.0234: » «, 0.0029: «r», 0.1484: «a», 0.0112: «y», 0.339: «i», 0.0045: «u»}, «y»: {0.204: «e», 1.0: » «, 0.0681: «i», 0.0136: «l», 0.0314: «t», 0.0223: «m», 0.303: «o», 0.0475: «a», 0.0056: «p», 0.1217: «s»}, «x»: {1.0: «p», 0.7464: » «, 0.0368: «u», 0.2706: «i», 0.1089: «c», 0.0215: «h», 0.01: «o», 0.5265: «t», 0.1895: «e», 0.3517: «i»}, «z»: {1.0: «e», 0.4678: » «, 0.2055: «o», 0.3289: «i», 0.0684: «y», 0.043: «u», 0.0075: «h», 0.024: «l», 0.6314: «a», 0.1182: «z»} }; // create a sorted list for all keys for(var key in grams){ var sorted = []; for(var p in grams[key]) sorted.push(p); grams[key].sorted = sorted.sort(); } function generateWords(n){ if(!n){ n = 1; } var words = []; for(var i=0; i<n; i++){ var w = ‘ ‘; // last will be our 1gram used to find a proper follower var last = w; while(true){ var rand = Math.random(); var p_list = grams[last].sorted; // find the follower corresponding to the random number // Note: p_list containes the accumulated probabilities of // the followers. for(var k=0; k+1 < p_list.length && p_list[k] < rand; k++); char = grams[last][p_list[k]]; if(char === ‘ ‘){ // space indicates end, but we do not want words shorter // than 5 so make sure we have minimum length if(w.length > 5) break; } else{ w += char; } last = char; } // strip the leading space before appending to the list words.push(w.substring(1)); } return words; }

JavaScript is a lightweight, cross-platform, interpreted scripting language. It is well-known for the development of web pages, many non-browser environments also use it. JavaScript can be used for Client-side developments as well as Server-side developments.

In this article, we need to create a Random String Generator using Javascript that will generate a random set of strings & get displayed when the user clicks a button. Additionally, we can also take input for the length of the string from the user. On the client-side, it will render those strings once generated using the Document Object Model (DOM) concept.

Approach: For generating Random Strings in Javascript, we can use in-built methods that will actually generate the strings and can manipulate the Document Object Model (DOM) accordingly. We will use the Math library to access the random() function that will help to generate the random index and multiple with the length of the string ie., it will append the character from the string or character set as it is passed. 

We can generate the random string in 2 ways ie., either we can iterate the loop for the specified length of the character set or we can use String.fromCharCode() method that will convert the UTF-16 codes into their equivalent characters and returns the string. By using the 2nd approach, we can manually take input for the length of the string from the user then generate the string of that particular length by accessing the DOM elements. For both approaches, we will use the Math.random() function.

Generating Random Strings: Here, we will generate strings only with lowercase letters characters. Let’s start by discussing the two different approaches for generating the strings.

Approach 1: Generating the random string from the specified length of the character set:

  • Declare the character set that will use for generating string.
  • Access the length of that character set from the input.
  • Construct the iteration loop for random character generation.
  • Use Math functions in javascript & assign them to the variable.

We will utilize the above concepts & generate the strings randomly of user-defined length using Javascript and DOM manipulation.

Defining the character set: We have defined a variable “characters” that will contain all the characters as we require. We will use another variable “result” which is initialized as an empty string.
Accessing the length of the string: After this, we will fetch the length of the string that we need to generate by using the document.getElementById method to access the HTML element or the user input field that contains the length.

length = document.getElementById("strlength").value;

So, we have used the “strlength” id which is declared inside the  HTML <input> tag. We can get the value of the element using the “.value” attribute and then assign it to a “length” variable. Thus, we have now obtained the length of the string that is needed to generate.

Generating Random characters: We will use a for loop to generate n(length) number of characters and append those to the string. The loop will run from 0 till length -1 as the index value start from 0.

for ( let i = 0; i < length; i++ ) {
        // Code
}

Now, we will use the Math.random() function to generate a random index in the string. Before that, we need to get the length of the “characters” string and store it in a const variable “charactersLength”. This will give us the length of the “charactersLength” string which is 26. Now, using the charAt() function that will return the character at a specified index in a string & we can get the random number.

The Math.random() function will give the value between 0 & 1 ie., decimal value & we need to round it off to get an integer value. Hence, we use Math.floor to round off the decimal value. We will multiply the Math.random() function with the variable charactersLength, to get the exact integer value. Thus, this will give us an integer between 0 and characterslength-1. 

Math.floor(Math.random() * charactersLength)

The above syntax will give the integer between 0 and the length of the charactersLength-1 as the strings in Javascript are 0 based indexing.

Hence, by using characters.charAt() method, we can get the character at that particular index. We finally add it to the empty string “result” and at the end of the loop, we get a string with random characters.

Example: This example describes the random number generation for the specified length of the character.

HTML

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>String Generator</title>

</head>

<body>

    <h2>Random String Generator</h2>

    <h4 id="target"></h4>

    <input id="strlength" type="number" value="5" min="1" max="100" />

    <button id="gen" onClick="generate()">Generate</button>

    <script>

    function generate() {

        let length = document.getElementById("strlength").value;

        const characters = 'abcdefghijklmnopqrstuvwxyz';

        let result = ' ';

        const charactersLength = characters.length;

        for(let i = 0; i < length; i++) {

            result += 

            characters.charAt(Math.floor(Math.random() * charactersLength));

        }

        document.getElementById("target").innerHTML = result

    }

    </script>

</body>

</html>

Output:

Approach 2: Generating the random string by using the String.fromCharCode() function:

  • Fetch the length of the string to be generated from the input.
  • Construct the iteration loop for the random character generation.
  • Use String and Math functions to generate characters.

We can use in-built functions like String.fromCharCode() function to generate a random Character. The step for declaring the character set & accessing its length will be similar to the first approach ie., we will create the length variable to get the length of the user input. After that, we create an empty string “result” for storing the generated string. We then run a for loop to iterate over the length of the string.

for ( let i = 0; i < length; i++ ) {
       // Code
}

Now, we use the function String.fromCharCode to generate characters one by one using the for loop. The String.fromCharCode takes in the integer or UTF-16 code units and gives the equivalent string. Here, we are using the integer 97 i.e. the starting point of lowercase letters. You can refer to the UTF-16 table to get the value of the lower case letters. So, getting that lowercase ‘a’ is 97 in UTF-16, we can add 26 to the number to get the last letter ‘z’ as 122. So, we simply need to generate 26 random numbers and add them to 97.

We can use the Math.random() function that returns a value between 0 and 1 and to get the integer value we need to floor() function to get the exact integer value & hence, we use the Math.floor(). But this will only get us 0 , every time we need to multiply the number Math.random() with 26 to get that desired result. 

97 + Math.floor(Math.random() * 26)

This will give the value between 97 and 122 i.e. ‘a’ to ‘z’. Thus, by enclosing them in the function String.fromCharCode() to get the actual string.

Displaying the generated Strings: We have displayed the string using the innerHTML property and by accessing the HTML element using its id value. So, using the “document.getElementById” method to get the element h4 with the id “target” from the HTML code and then access the HTML value using “.innerHTML”. We assign that value to the string “result” which is the randomly generated string. This will display the string in the HTML template.

document.getElementById("target").innerHTML = result;

Example: This example describes the random number generation using the String.fromCharCode() function.

HTML

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>String Generator</title>

</head>

<body>

    <h2>Random String Generator</h2>

    <h4 id="target"></h4>

    <input id="strlength" type="number" value="5" min="1" max="100" />

    <button id="gen" onClick="generate()">Generate</button>

    <script>

    function generate() {

        let length = document.getElementById("strlength").value;

        let result = ' ';

        for(let i = 0; i < length; i++) {

            result += 

            String.fromCharCode(97 + Math.floor(Math.random() * 26));

        }

        document.getElementById("target").innerHTML = result

    }

    </script>

</body>

</html>

Output:

Example 1: Generate Random Strings

// program to generate random strings

// declare all characters
const characters ='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

function generateString(length) {
    let result = ' ';
    const charactersLength = characters.length;
    for ( let i = 0; i < length; i++ ) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }

    return result;
}

console.log(generateString(5));

Output

B5cgH

In the above example, the Math.random() method is used to generate random characters from the specified characters (A-Z, a-z, 0-9).

The for loop is used to loop through the number passed into the generateString() function. During each iteration, a random character is generated.


Example 2: Generate Random Strings Using Built-in Methods

// program to generate random strings

const result = Math.random().toString(36).substring(2,7);
console.log(result);

Output

gyjvo

In the above example, built-in methods are used to generate random characters.

The Math.random() method generates the random number between 0 and 1.

In toString(36) method, 36 represents base 36. The toString(36) represents digits beyond 9 by letters.

The substring(2, 7) method returns five characters.

Note: In the above examples, the output varies each time because random characters are generated at every execution.

Like this post? Please share to your friends:
  • Phrases with the word taken
  • Pick out the metaphors from the following word combinations
  • Pick out from the story the english equivalents of the following words and word combinations
  • Phrases with the word take
  • Pick one word to live by