Search code examples
javascriptdesign-patternsrandomletters

Random letter sequencing with a pattern


I'd like get random letters together to generate weird words with a specified pattern like cvvcv (consonants and vowels). No consonant variations like th- sh- ch- etc needed.

The problem is, when I attempt to do one, I have to specify the length of the word. However, I want the number of characters in the output to be the same in the pattern. I mean the length would be pre-defined by the character number of the pattern.

An example with a fiddle would be great and much appreciated.


Solution

  • You can try this, too:

    function replacePattern(pattern) {
        var possibleC = "BCDFGHJKLMNPQRSTVWXZ";
        var possibleV = "AEIOUY";
    
        var pIndex = pattern.length;
        var res = new Array(pIndex);
    
        while (pIndex--) {
           res[pIndex] = pattern[pIndex]
             .replace(/v/,randomCharacter(possibleV))
             .replace(/c/,randomCharacter(possibleC));
        }
    
        function randomCharacter(bucket) {
            return bucket.charAt(Math.floor(Math.random() * bucket.length));
        }   
        return res.join("").toLowerCase();
    };
    

    https://jsfiddle.net/u2aooqf7/