Generating Random Text with JavaScript

April 26, 2023

Introduction

Random text generation is a useful feature in many applications, such as placeholder text, testing user interfaces, or generating dummy data for development purposes. JavaScript offers an easy way to create random text generators with different levels of complexity, from simple character sequences to more advanced and readable paragraphs. In this article, we'll explore two approaches for generating random text in JavaScript and see how we can extend the functionality to meet specific requirements.

Generating random strings of characters

The simplest way to create random text in JavaScript is to generate a random sequence of characters. We can achieve this by using the built-in Math.random() function in combination with a character set. Here's a function that generates a random string of a given length:

function generateRandomText(length) {
  const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let randomText = '';

  for (let i = 0; i < length; i++) {
    const randomIndex = Math.floor(Math.random() * charset.length);
    randomText += charset[randomIndex];
  }

  return randomText;
}

// Usage example:
const randomText = generateRandomText(10);
console.log(randomText);

Generating random text using a predefined set of words

While random character sequences might be useful in some scenarios, more advanced applications may require readable text. In this case, we can create a random text generator that uses a predefined set of words and combines them randomly to generate sentences and paragraphs. Here's an example:

function generateRandomText(numParagraphs, numSentencesPerParagraph) {
  const words = ['lorem', 'ipsum', 'dolor', 'sit', 'amet', 'consectetur', 'adipiscing', 'elit', 'sed', 'do', 'eiusmod', 'tempor', 'incididunt', 'ut', 'labore', 'et', 'dolore', 'magna', 'aliqua'];
  const paragraphs = [];

  for (let p = 0; p < numParagraphs; p++) {
    const sentences = [];

    for (let i = 0; i < numSentencesPerParagraph; i++) {
      const numWords = Math.floor(Math.random() * 10) + 5;
      const sentenceWords = [];

      for (let j = 0; j < numWords; j++) {
        const randomIndex = Math.floor(Math.random() * words.length);
        sentenceWords.push(words[randomIndex]);
      }

      const sentence = sentenceWords.join(' ') + '.';
      sentences.push(sentence.charAt(0).toUpperCase() + sentence.slice(1));
    }

    paragraphs.push(sentences.join(' '));
  }

  return paragraphs.join('\n\n');
}

// Usage example:
const randomText = generateRandomText(3, 5);
console.log(randomText);

See the result here at https://www.devtoolsdaily.com/text-generator/lorem-ipsum/