
Building a Mad Lib Engine With Template Literals and Part-of-Speech Tagging
Mad Libs seem like a trivial programming exercise. Replace placeholder words in a template with user input. Five minutes, right? Then you try to make it actually good, and you discover that natural language is full of edge cases that turn a toy project into a legitimate text processing challenge. The basic engine The simplest Mad Lib implementation uses template strings with placeholders: function madlib ( template , words ) { return template . replace ( / \{(\w + )\} /g , ( match , key ) => { return words [ key ] || match ; }); } const template = " The {adjective} {noun} {verb} over the {adjective2} {noun2}. " ; const words = { adjective : " purple " , noun : " elephant " , verb : " jumped " , adjective2 : " lazy " , noun2 : " fence " }; madlib ( template , words ); // "The purple elephant jumped over the lazy fence." This works but has problems. You need unique keys for every placeholder, which means the template author has to invent names like adjective2 and adjective3 . It does not
Continue reading on Dev.to JavaScript
Opens in a new tab




