mc0de
JavaScript · Lesson 10 of 17

JavaScript Strings

Turn ordinary text into something powerful! Learn to combine words, transform capitalization, search for phrases, and create dynamic messages with JavaScript.

Text Values Template Literals String Methods Text Formatting
● ● ●   strings.js
const message = "Hello, mC0de!";

console.log(
  message.toUpperCase()
);
STRING EXPLORER
> Ready to transform text…
01 / Getting Started

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.

Creating strings
const firstName = "Alex";
const city = 'Irvine';
const greeting = `Welcome to mC0de!`;

console.log(firstName);
console.log(city);
console.log(greeting);
Console output
Alex Irvine Welcome to mC0de!

All three examples create strings. The quote style doesn’t change the basic data type, but backticks offer additional features you’ll explore shortly.

Remember: Numbers inside quotes are strings. "25" is text, while 25 is a number. That difference matters when performing calculations.
02 / Combining Text

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.

Concatenation using +
const firstName = "Alex";
const lastName = "Morgan";

const fullName = firstName + " " + lastName;

console.log("Welcome, " + fullName + "!");
Console output
Welcome, Alex Morgan!

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.

Appending text
let message = "Hello";
message += ", developer!";
console.log(message);
Console output
Hello, developer!
03 / Template Literals

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 ${...}.

Inserting values into text
const name = "Alex";
const lessons = 10;

const message = `Hi ${name}! You've reached
lesson ${lessons} of JavaScript.`;

console.log(message);
Console output
Hi Alex! You’ve reached lesson 10 of JavaScript.

Template literals can also span multiple lines without using special newline characters.

Expressions inside template literals
const price = 12;
const quantity = 3;

console.log(`Total: $${price * quantity}`);
Console output
Total: $36
Helpful tip: Template literals are particularly useful when building personalized messages, receipts, notifications, and dynamic interface text.
04 / Length & Character Positions

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.

Length and indexes
const language = "JavaScript";

console.log(language.length);
console.log(language[0]);
console.log(language[4]);
Console output
10 J S

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.

Reading the final character
const word = "Coding";

console.log(word.at(-1));
Console output
g

Strings are immutable: you cannot change an individual character by assigning to its index. Instead, string methods produce new strings.

05 / Transforming 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.

Useful formatting methods
const text = "  Hello JavaScript  ";

console.log(text.trim());
console.log(text.toUpperCase());
console.log(text.toLowerCase());
Console output
Hello JavaScript HELLO JAVASCRIPT hello javascript

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.

Combining methods
const username = "  Alex  ";

const cleaned = username.trim().toLowerCase();

console.log(cleaned);
Console output
alex
Good habit: Use trim() before checking whether someone entered a meaningful value into a text field.
06 / Searching & Extracting

Find and Replace Parts of a String

Strings can be searched, sliced into smaller pieces, and updated through methods that return modified copies.

Searching inside text
const message = "Learn JavaScript with mC0de";

console.log(message.includes("JavaScript"));
console.log(message.indexOf("mC0de"));
console.log(message.startsWith("Learn"));
Console output
true 22 true

includes() checks whether text is present. indexOf() returns the first matching position, or -1 if nothing matches. startsWith() checks the beginning of a string.

Extracting and replacing text
const message = "Hello JavaScript";

console.log(message.slice(0, 5));
console.log(message.replace("Hello", "Welcome to"));
Console output
Hello Welcome to JavaScript

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.

07 / Strings in Real Websites

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.

Analyzing a message
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);
Console output
Learning JavaScript is fun! 27 4

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.

Live Text Analyzer

Type something, then select a transformation.

Your results will appear here.
Remember: When displaying text supplied by a visitor, use textContent instead of interpreting their input as HTML.
🚀 mC0de Challenge

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

  1. Add a textarea where visitors can type or paste text.
  2. Create a function named analyzeText() that reads the input.
  3. Display the character count using length.
  4. Calculate the word count using trim() and split().
  5. Add buttons for uppercase and lowercase formatting.
  6. Add a button to remove unnecessary spaces at the beginning and end.
  7. Display the transformed result on the webpage.
Extra challenge: Add a search field to count occurrences of a word or phrase, and a button that converts the text to Title Case.
💻 Interactive JavaScript Sandbox

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.

Live Result
Lesson 10 Recap

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(), and toLowerCase().
  • 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 Completed

Ten 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!