Skip to content

Instantly share code, notes, and snippets.

@jonny-harte
Last active September 21, 2022 16:55
Show Gist options
  • Save jonny-harte/3a13ec1ef0c48bfa695c0570b176e165 to your computer and use it in GitHub Desktop.
Save jonny-harte/3a13ec1ef0c48bfa695c0570b176e165 to your computer and use it in GitHub Desktop.
bookmarklet that analyzes the current page and determines the frequency of word usage.
javascript:(function () {
const
words = document.body.innerText.split(/\s+/), //get all words on the page.
filteredWords = words.filter(word => word.length >= 4).sort(), //filter out words smaller than 4 characters and sort alphabetically.
specialCharacters = /^[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]*$/, //list of special characters to remove from words.
div = document.createElement('div'), //create a div to contain the tag presentation.
style = document.createElement('style'); //create a style tag to contain the tag presentation styling.
let frequency = {};
//set class and style for the presentation tag.
div.className = 'word-frequency';
style.innerHTML = `.word-frequency {
background-color: #ffffff;
border: 3px solid #000000;
font-size: 16px;
max-height: 30%;
overflow: scroll;
padding: 5px;
position: fixed;
right: 0;
text-align: justify;
top: 0;
width: 300px;
z-index: 9999;
}`;
//add styles and container to the document.
document.head.appendChild(style);
document.body.appendChild(div);
//loop through each word, add object key if not present or increment the count.
filteredWords.forEach(
word => {
//remove special characters from start of word.
if (word.charAt(0).match(specialCharacters)) {
word = word.substr(1);
}
//remove special characters from end of word.
if (word.charAt(word.length - 1).match(specialCharacters)) {
word = word.slice(0, -1);
}
//if word exists increment word frequency, else add word to frequency object.
frequency[word] ? frequency[word] += 1 : frequency[word] = 1;
return frequency;
}
);
//convert to array of array to loop through.
frequency = Object.entries(frequency);
//loop through each word and add it to .word-frequency container div.
for (const [word, count] of frequency) {
const span = document.createElement('span');
span.innerText = word;
//if more than once occurrence of the word, increase the font-size as a percentage based on the count.
span.style.fontSize = (count !== 1 ? `${(count * 5 + 10) + 100}%` : '');
//add span and a space after to allow them to wrap inside the container.
div.appendChild(span);
div.appendChild(document.createTextNode(' '));
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment