Search code examples
javascriptlistselectrandomwords

How do I display 3 randomly selected words from a list in set order in Javascript?


The idea is to generate a random reverse acronym for the acronym 'REG' using a list of words that begin with 'R', 'E' and 'G'. Every time you visit the page that the code is on it should pick a word from each list and place them in the REG order (example: Rodent Echo Ghost, Ronald Evening Garden, etc.)

The result of the code should be displayed as text on a webpage ofcourse.

Optional would be the ability to choose the font family, size and colour.

I searched around for this kind of code but to no avail. Probably also good to mention that I don't have much experience with Javascript at all, so any help is appreciated.


Solution

  • You can use this code to get the string that you want. You can add in each array any number of words that start with the letters..

    Then, the variable acron will hold the string that you want. You can inject it wherever you need. Since I do not know what you want to do with it, I can't elaborate.

    var r=[
        "Rodent",
        "Ronald",
        "Robocop",
    ];
    
    var e=[
        "Echo",
        "Evening",
        "Everyone",
    ];
    
    var g=[
        "Ghost",
        "Garden",
        "Green"
    ]
    
    var randr=Math.floor((Math.random() * r.length) );
    var rande=Math.floor((Math.random() * e.length) );
    var randg=Math.floor((Math.random() * g.length) );
    
    var acron=r[randr]+" "+e[rande]+" " + g[randg];
    

    fiddle