DEV Community

Cover image for Create Your Own Ipsum Generator With JavaScript
Dev By RayRay
Dev By RayRay

Posted on • Originally published at hasnode.byrayray.dev on

Create Your Own Ipsum Generator With JavaScript

Generating content with random words can be convenient for testing purposes. That's why today, we will create a function that does that.

Use this code to build your own Ipsum generator, so you have random generated content as much as you like πŸ‘

You could use a library if you want, but since this is so simple and can be built with not so many lines of code, it's nice to make it yourself.

For generating content with random words, we need three functions and a source of the phrase.

  1. A function that gives us a random number
  2. A function that gives us a random word
  3. A function that puts multiple words into a string
  4. The source for the words will be a defined Array with words. (Get it from my Gist)

divider-byrayray.png

1. Generate Random Number

Since we want to get a random word from our source, we need to generate a random index number. With this function, we need to keep in mind what the minimal and maximum of the Array are.

Math.random();
// Returns 0.534098468876492
Enter fullscreen mode Exit fullscreen mode

With Math.random(), we get a random float between 0 and lower than 1. When we multiply that by, for example, 10, we will get a number between 0 and lower than 10. But in this case, we want to have a number not lower than 0 and lower or equal than 10.

Math.random() * (10 - 0) + 0;
// Returns 8.448742196214798
Enter fullscreen mode Exit fullscreen mode

But right now, it still returns afloat. So we have to use Math.round to get an integer.

Math.round(Math.random() * (10 - 0) + 0)
// Returns 6 or 5 or 9 or 10
Enter fullscreen mode Exit fullscreen mode

With this calculation, we can get a number between 0 and 10 or equal to 10. You can test that quickly if it does what you expect.

let number = 0;
let steps = 0;
while(number != 10) {
    number = Math.round(Math.random() * (10 - 0) + 0);
    steps = steps + 1;
    console.log('steps', steps)
}
Enter fullscreen mode Exit fullscreen mode

With this code, you are running a loop until it becomes 10. By keeping track of the steps, you can see how many rounds it needs. Every time you run this, you will know that it requires a different amount of rounds.

function randomNumber(min, max) {
    return Math.round(Math.random() * (max - min) + min);
}
Enter fullscreen mode Exit fullscreen mode

This is this final function to get a random number between two numbers. Let's continue to get a random word from our source, Array.

divider-byrayray.png

2. Get Random Word

I found a nice collection of random words to use for this post. You can find it on Gist. But in this post, I will use a shorter version.

You can also define your own words in a certain theme. For example Developer Ipsum or Cupcake Ipsum

const word = [
    "Got",
    "ability",
    "shop",
    "recall",
    "fruit",
    "easy",
    "dirty",
    "giant",
    "shaking",
    "ground",
    "weather",
    "lesson",
    "almost",
    "square",
    "forward",
    "bend",
    "cold",
    "broken",
    "distant",
    "adjective."
]
Enter fullscreen mode Exit fullscreen mode

We need to use the randomNumber function that we created in the previous step to get a random word. In this function, we need to give a minimum and a maximum number as parameters; we can easily do that via this.

const word = words[randomNumber(0, words.length - 1)];
Enter fullscreen mode Exit fullscreen mode

The first parameter is 0 because of the Array's start with 0. The second parameter is our maximum, so we pick the words.length - 1. We do this because, in this example, our Array has 20 words in it so that the length property will give that back. But since an Array starts with counting from 0, the latest position in the Array is 19. That's why we do - 1.

function getRandomWord() {
    return words[randomNumber(0, words.length - 1)];
}
Enter fullscreen mode Exit fullscreen mode

We have our second function to get a random word from the words Array.

divider-byrayray.png

3. Get A String With Random Words

Now we want to get multiple words and make it a string, so we can use it as content for whatever we want. The best we can do that is by generating an Array with several positions.

[...Array(10)]
// Returns [undefined, undefined, ....] with 10 items
Enter fullscreen mode Exit fullscreen mode

With the .map method, we can iterate and fill it with random words.

[...Array(10)].map(() => getRandomWord())
// Returns ["hand", "close", "ship", "possibly", "metal", "myself", "everybody", "serious", "adult", "favorite"]
Enter fullscreen mode Exit fullscreen mode

Now that we have an Array of random words, we need to turn it into a string using the .join('').

[...Array(10)].map(() => getRandomWord()).join('')
Enter fullscreen mode Exit fullscreen mode

But, we want to give the string some "sense" of its readability. So every first word in the Array should have the first letter as uppercase. Let’s update our getRandomWord function.

function getRandomWord(firstLetterToUppercase = false) {
    const word = words[randomNumber(0, words.length - 1)];
    return firstLetterToUppercase ? word.charAt(0).toUpperCase() + word.slice(1) : word;
}
Enter fullscreen mode Exit fullscreen mode

As we create a function to generate a function to get the generated string, it would look like this. With the comparison in the getRandomWord(i === 0) we give a boolean through the function.

function generateWords(length = 10) {
    return [...Array(length)].map((_, i) => getRandomWord(i === 0)).join(' ').trim() + '.';
}

Enter fullscreen mode Exit fullscreen mode

divider-byrayray.png

4. Complete

Now that we created all the code, it's time to check the complete code example.

const word = [
    "Got",
    "ability",
    "shop",
    "recall",
    "fruit",
    "easy",
    "dirty",
    "giant",
    "shaking",
    "ground",
    "weather",
    "lesson",
    "almost",
    "square",
    "forward",
    "bend",
    "cold",
    "broken",
    "distant",
    "adjective."
]

function getRandomWord(firstLetterToUppercase = false) {
    const word = words[randomNumber(0, words.length - 1)];
    return firstLetterToUppercase ? word.charAt(0).toUpperCase() + word.slice(1) : word;
}

function generateWords(length = 10) {
    return [...Array(length)].map((_, i) => getRandomWord(i === 0)).join(' ').trim() + '.';
}

function randomNumber(min, max) {
    return Math.round(Math.random() * (max - min) + min);
}

Enter fullscreen mode Exit fullscreen mode

Try the function in this runkit example:

https://runkit.com/devbyrayray/how-to-generate-a-string-with-random-words

divider-byrayray.png

Thanks!

hashnode-footer.pngI hope you learned something new or are inspired to create something new after reading this story! πŸ€— If so, consider subscribing via email (scroll to the top of this page) or follow me here on Hashnode.

Did you know that you can create a Developer blog like this one, yourself? It's entirely for free. πŸ‘πŸ’°πŸŽ‰πŸ₯³πŸ”₯

If I left you with questions or something to say as a response, scroll down and type me a message. Please send me a DM on Twitter @DevByRayRay when you want to keep it private. My DM's are always open 😁

Top comments (0)