Home For Fiction – Blog

for thinking people

There are no ads, nor any corporate masters
How to show support


June 6, 2020

A JavaScript Random Text Generator

Programming

computer, javascript, literature, programming, writing

2 comments

Virtually all of my coding revolves around text, one way or another. Just to name two examples, see my rhyming anapest generator or my Gothic analyzer program. In this post, I decided to make something a bit mad, so I came up with a very simple (but very funny!) JavaScript random text generator.

But this isn’t just any random… random text generator like, say, my random quote generator. This little program – in only 10 lines of code – combines text from different sources and returns a set of randomized sentences.

If this sounds somewhat familiar, it’s very similar to my Ghostwriter Android app.

The difference is, this time I decided to i) code it in JavaScript (rather than Java); ii) use the first two chapters of two of my novels, Illiterary Fiction and The Other Side of Dreams to generate the results.

JavaScript random text generator
Why write a text with a pen, when you can write it with a JavaScript random text generator [/tongue-in-cheek]

A JavaScript Random Text Generator: the Code

Let’s first see the code right away. As I said, it’s only 10 lines. However, this is only possible because of the excellent RiTa library, which is a must for anyone coding with text.

<html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rita/1.3.94/rita-small.min.js"></script>
<script src="textCombo.txt"></script>
<script>
var rm = new RiMarkov(5);
rm.loadText(text);
sentences = rm.generateSentences(5);
for (i = 0; i < sentences.length; i++)
  document.write(sentences[i] + " ");
</script>
</html>

Yeah, I know. It shows 11 lines – but hey, remove the html tags, and it’s 10. About… Well, 10 is a nice round number, right?

Line 2 above loads the RiTa library. Line 3 loads the text file containing the first two chapters of my novel. If you know JavaScript, you must feel confused by this – why am I loading as a script src a .txt file?

Loading the Two Chapters

It’s a little trick to avoid the cross-origin request (CORS) issue when running scripts locally. The textCombo.txt begins with let text = ` followed by the entire text (i.e. the two chapters) and ending with `;

Then, as you notice on line 6, the variable text (the two chapters) is neatly passed as a parameter.

If you’re working with something similar online, something like this would do the trick:

var myText = getMyText();
function getMyText() {
    jQuery.get('http://example.com/myText.txt', function(data) {
        return data; 
});
}

Obviously, in such a case there’s no need for the text file to begin with let text = `

Combining Sentences and Getting Results

Lines 5 to 7 are where the whole process materializes (and where RiTa comes into play).

var rm = new RiMarkov(5); will do our random text generation via so-called Markov chains (or n-grams). Feel free to check the relevant RiTa documentation page for more. The number (5) indicates the length of each n-gram. In practical terms, longer numbers generate more coherent but less randomized sentences. I’ll show you examples below.

Lines 6 and 7 generate the sentences (5, in this example). Simple!

What this JavaScript Random Text Generator Returns

This is one example of what the code generated with the parameters above:

Nobody reads these days, and even those that do, just read the old classics. She got up, and Ahmed stood up too, ready to say goodbye. And then the human figures pass him by silently, and this is not Paul, and he isn’t the professional reader of this media house. He opens his khaki backpack and squeezes in as many books as he can. The main character, Hidetoshi, moves through life too timidly, being in a sense too polite to disrupt the brutality around him.

Let’s see what happens if we increase randomness (but also the likelihood that the sentences are more incoherent). I now use var rm = new RiMarkov(3); which means we have shorter n-grams.

A rancid smell of abandonment trailing behind him had heard everything, Ahmed thought, terrified that he caught a fleeting glimpse of her heart. What do we need to know about this book, perhaps the man was born. Nobody reads these days, and the roaring New York traffic again begins to pulsate along the short corridor, pushes the heels of his colleagues. He’s not willing to try, held back by the unexpected ordeal as he expected, a voice in his hand, and unscrewed the cap. The time was nine sharp, and he hadn’t cried there either, as it was the wrong place and came back.

Depending on the texts in question, it’s a matter of finding a balance between randomness and coherence.

Other Examples

For a more visual case, take a look at the… “Kafgenstein” example on the homepage of the RiTa library. As the name perhaps suggests, it combines texts from Kafka and Wittgenstein, deployed using the p5js graphics library – the same I use on the Bookworming Party project.

Wanna see what the original novels look like? Why don’t you download from Amazon a copy of Illiterary Fiction or The Other Side of Dreams and find for yourself. Or, if you prefer, you can email me and request a free digital copy. Another option:

Most of my novels are available as an immediate free download – simply visit the Fiction page on the main site. And remember, you can also just email me and ask for a free, no-strings-attached (e.g. review etc.) digital copy of any of my books.

Using Your Own Texts

If you want to try the code with your own texts, you now have the option!

Click to run the program

Note: The program is hosted on raw.githack. Since it’s a free service, 100% uptime cannot be guaranteed. If the program doesn’t appear above , please try later.

2 Comments

  1. The more random one appears to create very inspring content.Love it. Could be a great tool to spark creativity (i.e. a sort of “random random writing prompt”).

    1. Chris🚩 Chris

      Good idea, thanks for your comment!


Punning Walrus shrugging

Comments are closed for posts older than 90 days