home ~ projects ~ socials

Random Word Shape Text Generator

This little function generates random letters in the shape of paragraphs to fill up text areas for examples.

The goal is to make it as small as possible while providing something that looks like text if you squint at it.

HTML

<div><strong>Example 1</strong></div>
<div class="output-example flow"></div>

<div><strong>Example 2</strong></div>
<div class="output-example flow"></div>

<div><strong>Example 3</strong></div>
<div class="output-example flow"></div>

Output

Example 1
Example 2
Example 3

JavaScript

function genText(pMin, pMax, selector) {
  const letters = "abcdefghijklmnopqrstuvwxyz";
  const sCounts = [2, 4];
  const wCounts = [1, 6];
  const wLengths = [1, 2, 3, 4, 5, 6];
  const wWeights = [3, 10, 25, 45, 45, 30];
  for (let i = 1; i < wWeights.length; i++)
        wWeights[i] += wWeights[i - 1];
  const els = document.querySelectorAll(selector);
  els.forEach((el) => {
    const paragraphs = [];
    const pCount = Math.floor(Math.random() * (pMax - pMin + 1) + pMin - 1);
    for (let p = 0; p <= pCount; p ++) {
      const sentences = [];
      const sCount = Math.floor(Math.random() * (sCounts[1] - sCounts[0] +1)  + sCounts[0] - 1);
      for (let s = 0; s <= sCount; s ++) {
        const words = [];
        const wCount = Math.floor(Math.random() * (wCounts[1] - wCounts[0] +1)  + wCounts[0] - 1);
        for (let w = 0; w <= wCount; w ++) {
          let random = Math.random() * wWeights[wWeights.length - 1] + 1;
          for (let i = 0; i < wWeights.length; i++) {
            const word = [];
            if (wWeights[i] > random) {
              for (let l = 0; l <= wLengths[i]; l++) {
                word.push(letters.charAt(Math.floor(Math.random() * letters.length)));
                if (l === 0 && w === 0) {
                  word[0] = word[0].toUpperCase();
                }
              }
              words.push(word.join(""));
              break;
            }
          }
        }
        sentences.push(words.join(" ") + "." );
      };
      paragraphs.push(sentences.join(" "));
    };
    el.innerHTML = paragraphs.join("\n");
  });
}

genText(2,4, ".output-example");

The specific letters are all random. They work fine if you only need the shape of a paragraph for squinting at.

Lorem Ipsum text is probably better in most cases if you're gonna be close enough to read. That requires a bigger function, though.

-a

-- end of line --