JavaScript Strings
Turn ordinary text into something powerful! Learn to combine words, transform capitalization, search for phrases, and create dynamic messages with JavaScript.
const message = "Hello, mC0de!";
console.log(
message.toUpperCase()
);
What Is a JavaScript String?
Almost every website contains text: usernames, headings, messages, product descriptions, and search queries. JavaScript needs a way to store and work with that text. That’s where strings come in.
A string is a sequence of characters. You can create one using single quotes, double quotes, or backticks.
const firstName = "Alex";
const city = 'Irvine';
const greeting = `Welcome to mC0de!`;
console.log(firstName);
console.log(city);
console.log(greeting);All three examples create strings. The quote style doesn’t change the basic data type, but backticks offer additional features you’ll explore shortly.
"25" is text, while 25 is a number. That difference matters when performing calculations.Join Strings Together
Imagine welcoming someone to your website by name. Instead of writing a separate greeting for every visitor, you can combine strings with variables. This is called concatenation.
const firstName = "Alex";
const lastName = "Morgan";
const fullName = firstName + " " + lastName;
console.log("Welcome, " + fullName + "!");Notice the string containing a single space between the names. JavaScript doesn’t automatically insert spaces when joining strings.
You can also use += to append more text to a variable declared with let.
let message = "Hello";
message += ", developer!";
console.log(message);Build Messages With Backticks
Combining many pieces of text using plus signs can become difficult to read. Template literals offer a cleaner approach.
Template literals use backticks and allow you to insert JavaScript expressions using ${...}.
const name = "Alex";
const lessons = 10;
const message = `Hi ${name}! You've reached
lesson ${lessons} of JavaScript.`;
console.log(message);Template literals can also span multiple lines without using special newline characters.
const price = 12;
const quantity = 3;
console.log(`Total: $${price * quantity}`);Count and Access Characters
Strings have a length property that reports the number of UTF-16 code units in the text. For ordinary English letters, this generally matches the character count.
const language = "JavaScript";
console.log(language.length);
console.log(language[0]);
console.log(language[4]);Like arrays, strings use zero-based indexing. The first position is zero, not one.
You can use at() to read a character from the end of a string.
const word = "Coding";
console.log(word.at(-1));Strings are immutable: you cannot change an individual character by assigning to its index. Instead, string methods produce new strings.
Change Capitalization and Clean Up Text
Visitors rarely enter text in exactly the same format. One person may type all capital letters, while another may add extra spaces. JavaScript provides methods to help standardize text.
const text = " Hello JavaScript ";
console.log(text.trim());
console.log(text.toUpperCase());
console.log(text.toLowerCase());trim() removes whitespace from both ends. toUpperCase() converts letters to uppercase, while toLowerCase() converts them to lowercase.
These methods return new strings. They do not change the original string stored in text.
const username = " Alex ";
const cleaned = username.trim().toLowerCase();
console.log(cleaned);trim() before checking whether someone entered a meaningful value into a text field.Find and Replace Parts of a String
Strings can be searched, sliced into smaller pieces, and updated through methods that return modified copies.
const message = "Learn JavaScript with mC0de";
console.log(message.includes("JavaScript"));
console.log(message.indexOf("mC0de"));
console.log(message.startsWith("Learn"));includes() checks whether text is present. indexOf() returns the first matching position, or -1 if nothing matches. startsWith() checks the beginning of a string.
const message = "Hello JavaScript";
console.log(message.slice(0, 5));
console.log(message.replace("Hello", "Welcome to"));slice(0, 5) extracts positions zero through four. The ending index is not included.
replace() replaces the first matching string. Use replaceAll() when you need to replace every occurrence of a string.
Turn User Input Into Useful Information
Now it’s time to put these methods together. A text analyzer can take a visitor’s message and calculate its length, word count, and formatted versions.
const message = " Learning JavaScript is fun! ";
const cleaned = message.trim();
const words = cleaned
? cleaned.split(/\s+/).length
: 0;
console.log(cleaned);
console.log(cleaned.length);
console.log(words);The split(/\s+/) expression separates text wherever one or more whitespace characters appear. The result is an array of words, and its length tells us how many were found.
Try a simplified analyzer below.
Type something, then select a transformation.
textContent instead of interpreting their input as HTML.Build a Text Formatter & Analyzer
Create a mini text utility where visitors can enter a message, see useful statistics, and transform the text with one click.
Your Mission
- Add a textarea where visitors can type or paste text.
- Create a function named
analyzeText()that reads the input. - Display the character count using
length. - Calculate the word count using
trim()andsplit(). - Add buttons for uppercase and lowercase formatting.
- Add a button to remove unnecessary spaces at the beginning and end.
- Display the transformed result on the webpage.
Build Your Text Formatter!
Edit the JavaScript and test it in the live preview. The starter includes character counting, word counting, and formatting buttons. Load Solution adds phrase searching and Title Case.
What You’ve Learned
You’re Becoming a Text-Processing Pro!
You now know how to create strings, combine values, format text, search for phrases, and build useful text-processing features.
- Create strings using quotes and backticks.
- Combine strings with concatenation and template literals.
- Access characters and measure string length.
- Format text with
trim(),toUpperCase(), andtoLowerCase(). - Search, extract, and replace parts of strings.
- Count words using
split(). - Build an interactive Text Formatter & Analyzer.
Next up: The DOM — learn how JavaScript finds, changes, creates, and removes HTML elements!
Your Learning Journey
0 / 17 CompletedTen lessons into the pathway! Keep building your JavaScript skills.
You're Past the Halfway Point!
You've learned how to create, combine, search, and transform JavaScript strings. You've also built your own interactive Text Formatter & Analyzer. Ten lessons down, seven to go!


