Post

I am learning Javascript!

Today I decided to start learning Javascript, by making a small tool. I decided to make a character counter.

I started by making a basic character counter. It counts the amount of characters in a string.

1
2
3
4
5
6
7
8
function updateText() {
    let outputLabel = document.getElementById("output");
    let textField = document.getElementById("input");

    let text = textField.value;
    let count = text.length;
    outputLabel.innerText = count;
}

This script takes the input from a textarea and counts the amount of characters in it.

Here is a preview:

Character counter preview

Then I added a word counter.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function updateWordCount(){
    let wordLabel = document.getElementById("wordCount");
    let textField = document.getElementById("input");

    let text = textField.value;

    let words = text.split(" ");

    let wordCount;
    if (words[words.length - 1] == "") {
        wordCount = words.length - 1;
    } else {
        wordCount = words.length;
    }

    wordLabel.innerHTML = wordCount;
}

This code splits the text into words and counts the amount of words. It also ignores empty strings. This is so that if you type a sentence with a space at the end, it won’t count the empty string as a word.

Here is a preview:

Word counter preview

As a last feature, I added a “Common words” list. This list shows the top 10 most common words in your text.

1
2
3
4
5
6
7
8
9
10
11
function updateWordList() {
    let wordListHolder = document.getElementById("wordList");
    let textField = document.getElementById("input");

    let wordList = getWordCount(textField.value.toLowerCase().split(" "));

    for (item of sortDictionary(wordList).slice(0, 10)) {
        wordListHolder.innerHTML += `
        <p class="center">${capitalizeFirstLetter(item)}: ${wordList[item]}</p>`;
    }
}

It first gets a list of the words in the text. Then it creates a dictionary with the words as keys and the amount of times they appear as values. Then it sorts the dictionary by the amount of times they appear, and it gets the top 10 words.

Here is a preview:

Word list preview

This is a realy simple tool, but I think it’s a good start to learn Javascript. I hope you enjoy it!

Want to try my tool out? You can find it here.

Want to check the source code? You can find it here.

This post is licensed under CC BY 4.0 by the author.

Trending Tags