JavaScript Project Ideas: Text Analyzer
This program analyzes a given text and reports the number of words, the number of characters and the average word length. It is a perfect starter among javascript project ideas and a handy source of javascript exercises for beginners. Read the code, try the live demo, then solve the practice exercises.
How the JavaScript Text Analyzer Works
The analyzer is one of the best javascript project ideas for learning, because it practices the basics in a single small program: variables hold the data, a function does the work, and a loop adds up the word lengths. Any text you want to analyze can be passed to the analyzeText() function, and the program returns the total number of characters, the total number of words and the average word length.
If you are searching for javascript exercises for beginners, javascript tasks for practice or quick js exercises you can finish in one sitting, this project fits all three. The sections below walk through the code, how to run it, a working demo and javascript practice exercises with solutions.
What the finished project does
- Cleans the text by trimming the ends and collapsing repeated spaces between words.
- Counts characters and words in the cleaned text.
- Calculates the average word length and shows it with two decimals.
- Runs anywhere: in Node.js, in the browser console and on a web page.
analyzeText() now returns an object instead of only printing, so you can reuse the numbers. Printing moved to printAnalysis(). An empty string now returns zeros instead of NaN, because ''.split(' ') counts as one word.Step 1: The analyzeText() Function
The analyzeText() function accepts a text string as input. It first cleans the text by removing leading and trailing whitespace and extra spaces between words. The cleaned text is then split into an array of words, the program iterates through that array, and it calculates the number of characters, the number of words and the average word length. This is also a good javascript function exercise: take a string in, return a result.
function analyzeText(text) {
// Remove leading/trailing whitespace and extra spaces between words
const cleanedText = text.trim().replace(/\s+/g, ' ');
// An empty text has no words, so return zeros instead of NaN
if (cleanedText === '') {
return { text: '', characterCount: 0, wordCount: 0, averageWordLength: 0 };
}
// Calculate the number of characters
const characterCount = cleanedText.length;
// Calculate the number of words
const words = cleanedText.split(' ');
const wordCount = words.length;
// Calculate the average word length
let totalWordLength = 0;
for (let i = 0; i < wordCount; i++) {
totalWordLength += words[i].length;
}
const averageWordLength = totalWordLength / wordCount;
return { text: cleanedText, characterCount, wordCount, averageWordLength };
}
// Display the analysis results in the console
function printAnalysis(result) {
console.log('Text:', result.text);
console.log('Number of characters:', result.characterCount);
console.log('Number of words:', result.wordCount);
console.log('Average word length:', result.averageWordLength.toFixed(2));
}
// Example usage
const text = 'This is an example text for analysis.';
printAnalysis(analyzeText(text));Notice the variables in the function: cleanedText, characterCount, wordCount and totalWordLength. They make a compact set of javascript variables exercises for beginners, because each one stores a different kind of value (a string, two counts and a running total).
Step 2: Run the Program
Save the program’s code in a JavaScript file, such as text_analysis.js, and run the following command at a command prompt or terminal. You can also paste the code into your browser’s developer console.
node text_analysis.jsFor the example text, the output looks like this:
Text: This is an example text for analysis.
Number of characters: 37
Number of words: 7
Average word length: 4.43The count includes the final period, so analysis. has 9 characters. To ignore punctuation, strip it with replace(/[^\w\s]/g, '') before splitting the text into words. That small change is a good js exercise of its own.
Step 3: Show the Analysis on a Web Page
To turn the console program into something visitors can click, connect the same function to a textarea. This minimal page loads text_analysis.js and prints the result with textContent, so pasted text can never inject HTML into the page.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Text Analyzer</title>
</head>
<body>
<textarea id="input" rows="5" cols="40">This is an example text for analysis.</textarea>
<button id="go">Analyze</button>
<pre id="out"></pre>
<script src="text_analysis.js"></script>
<script>
document.getElementById('go').addEventListener('click', () => {
const r = analyzeText(document.getElementById('input').value);
document.getElementById('out').textContent =
'Characters: ' + r.characterCount + '\n' +
'Words: ' + r.wordCount + '\n' +
'Average word length: ' + r.averageWordLength.toFixed(2);
});
</script>
</body>
</html>Live Demo: Text Analyzer in Action
This demo runs the same logic as the code above, plus a few extra statistics. Type or paste any text and the results update instantly. Nothing is sent anywhere: the analysis happens in your browser.
Most frequent words
Console report
How to Turn This JavaScript Project into a Portfolio Piece
A working analyzer is a good start, but how you present it matters just as much. Hiring managers look for evidence that you can finish a project and explain your decisions.
- Publish the code on GitHub with a README that explains what it does and how to run it.
- Host the live demo on GitHub Pages and link it from your portfolio.
- Explain your choices: why the function returns an object and how empty text is handled.
- Add tests for known inputs, such as the 37 characters and 7 words in the example.
Ideas to extend the analyzer
- Count sentences, paragraphs and unique words.
- Show the most frequent words as a chart.
- Add a readability score such as Flesch reading ease.
- Support several languages, including right-to-left text.
JavaScript Exercises and Solutions Based on the Text Analyzer
The analyzer is a great source of javascript exercises because every part practices a core idea. If you want javascript practice exercises with solutions, try each task yourself first, then open the solution to compare. These js exercises build on each other, from variables to functions to objects.
Javascript variables exercises and function exercises
Begin with exercise 1 (variables) and exercise 2 (functions). They are classic javascript exercises for beginners and take only a few minutes each.
1. Variables: count the vowels
A javascript variables exercise: store a string in a variable and count its vowels.
const text = 'JavaScript exercises';
const vowels = (text.match(/[aeiou]/gi) || []).length;
console.log(vowels); // 72. Function: find the longest word
A javascript function exercise: write longestWord(text) that returns the longest word.
function longestWord(text) {
return text.split(/\s+/).reduce((a, b) => (b.length > a.length ? b : a), '');
}
console.log(longestWord('I love JavaScript functions')); // JavaScript3. Task: capitalize every word
One of the quickest javascript tasks for practice: turn the first letter of each word into a capital.
const capitalize = (text) =>
text.split(' ').map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(' ');
console.log(capitalize('learn js every day')); // Learn Js Every Day4. Challenge: most frequent word
A js exercise with objects: return the word that appears most often.
function mostFrequent(text) {
const counts = {};
for (const w of text.toLowerCase().split(/\s+/)) {
counts[w] = (counts[w] || 0) + 1;
}
return Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
}
console.log(mostFrequent('to be or not to be')); // to5. Challenge: palindrome check
Ignore case and punctuation, then compare the text with its reverse.
const isPalindrome = (s) => {
const c = s.toLowerCase().replace(/[^a-z0-9]/g, '');
return c === [...c].reverse().join('');
};
console.log(isPalindrome('A man, a plan, a canal: Panama')); // trueLooking for more javascript exercises and solutions? Browse our JavaScript projects and the free PDF practice sets.
Frequently Asked Questions About JavaScript Projects
What can you do with JavaScript?
JavaScript builds interactive websites, web apps, browser games, server applications with Node.js, mobile apps and small tools such as this text analyzer.
How long does it take to learn JavaScript?
Most beginners learn the basics (variables, functions, loops, arrays) in a few weeks of regular practice, and become comfortable building projects after a few months.
Is JavaScript for beginners, and how hard is it?
Yes. You see results instantly in the browser console, and the basics are easy. Harder topics such as asynchronous code take more practice, so start with small projects and javascript exercises for beginners.
Is JavaScript still needed?
Yes. It is the standard language of the web, runs in every browser, and is widely used on servers through Node.js.
How do I run a JavaScript file?
Save the code as text_analysis.js and run node text_analysis.js in a terminal, or paste the code into your browser’s developer console.
Where can I find JavaScript exercises and solutions?
Use the five exercises with solutions on this page, then browse the JavaScript projects on Darekdari for more practice exercises.
JavaScript FAQ in Turkish, Spanish, German and Arabic
Many learners search for JavaScript project ideas in their own language, so here are short answers to the most common questions.
Türkçe: JavaScript projeleri
JavaScript ile neler yapılabilir?
JavaScript ile web siteleri, mobil uygulamalar, oyunlar, Node.js ile sunucu uygulamaları ve metin analizi gibi küçük araçlar geliştirebilirsiniz.
JavaScript öğrenmek ne kadar sürer?
Temel konuları öğrenmek genellikle birkaç hafta, rahatça proje geliştirmek ise birkaç ay düzenli pratik gerektirir.
JavaScript hangi program?
JavaScript bir programlama dilidir. Tarayıcıda veya Node.js ile çalışır; kod yazmak için Visual Studio Code gibi bir editör yeterlidir.
JavaScript neden popüler?
Her tarayıcıda çalıştığı, öğrenmesi kolay olduğu ve hem ön yüzde hem arka yüzde kullanılabildiği için popülerdir.
Español: proyectos en JavaScript
¿Qué proyectos se pueden hacer con JavaScript?
Calculadoras, carritos de compra, analizadores de texto, juegos, aplicaciones del clima y mucho más.
¿Qué es un proyecto en JavaScript?
Es un programa o página web escrito con JavaScript que combina variables, funciones y clases para resolver un problema concreto.
¿Cómo empezar un proyecto de JavaScript?
Crea un archivo .js, escribe una función pequeña como analyzeText() y ejecútala con Node.js o en la consola del navegador.
¿Qué programas se han hecho con JavaScript?
Sitios web, aplicaciones web, juegos de navegador, servidores con Node.js y aplicaciones de escritorio con Electron.
Deutsch: JavaScript lernen
Wird JavaScript noch benötigt?
Ja. JavaScript ist die Standardsprache des Webs, läuft in jedem Browser und wird mit Node.js auch auf Servern breit eingesetzt.
Was kann man alles mit JavaScript machen?
Websites, Web-Apps, Spiele, Server-Anwendungen, mobile Apps und kleine Tools wie einen Textanalysator.
Ist JavaScript für Anfänger?
Ja. Man sieht Ergebnisse sofort im Browser, und kleine Projekte erleichtern den Einstieg.
Wie schwierig ist JavaScript?
Die Grundlagen sind leicht zu lernen. Fortgeschrittene Themen wie asynchrone Programmierung brauchen mehr Übung.
العربية: مشاريع جافا سكريبت
تبحث عن مشاريع جافا سكريبت للمبتدئين؟ محلل النصوص هذا مثال بسيط على مشروع جافا سكريبت يمكنك تجربته مباشرة وتعديل شيفرته. يمكنك أيضاً البحث عن مشاريع جافا سكريبت جاهزة pdf للحصول على شروحات مكتوبة، أو البحث عن مشروع جافا سكريبت github للعثور على شيفرات مفتوحة المصدر.
لست بحاجة إلى جافا سكريبت تحميل أو تحميل جافا سكريبت للاندرويد، فهي تعمل داخل المتصفح مباشرة، ويكفي تطبيق محرر أكواد إذا أردت الكتابة من الهاتف. أما تفعيل جافا سكريبت على الهاتف فيتم من إعدادات المتصفح إذا كانت معطّلة. وللتوسع جرّب مشاريع جافا للمبتدئين، مع ملاحظة أن جافا وجافا سكريبت لغتان مختلفتان.
Keep Building with JavaScript
You built a text analyzer with one reusable function, ran it in Node.js and in the browser, and practiced with javascript exercises and solutions. Small javascript project ideas like this one are the fastest way to learn, and with a README and a live demo they make a solid portfolio addition.
