javascript-course-chapter-08
Chapter 8: Strings
Learn JavaScript strings with beginner-friendly explanations, examples, outputs, and fully commented code.
Goal: Understand how to create, read, search, change, split, trim, and optimize text in JavaScript.
8.1 Creating Strings
A string is text in JavaScript. You use strings for names, messages, emails, addresses, titles, and user input.
Strings can be written with double quotes, single quotes, or backticks.
For beginners, double quotes are very common, but template literals with backticks are powerful for inserting variables.
Example 1: String with double quotes
// Create a string using double quotes.
let courseName = "JavaScript";
// Print the string.
console.log(courseName);
// Output:
// JavaScript
Explanation:
The text JavaScript is inside quotes, so JavaScript treats it as a string value.
Example 2: String with single quotes
// Create a string using single quotes.
let studentName = 'Ali';
// Print the string.
console.log(studentName);
// Output:
// Ali
Explanation:
Single quotes also create strings. The important rule is to start and end with the same quote type.
8.2 Escape Characters
Escape characters help you write special characters inside strings.
They are useful when you need quotes inside quotes, new lines, tabs, or special formatting.
In JavaScript, escape characters usually start with a backslash.
Example 1: Quote inside string
// Use backslash to show quotes inside a string.
let message = "He said, \"Hello!\"";
// Print the message.
console.log(message);
// Output:
// He said, "Hello!"
Explanation:
The backslash tells JavaScript that the quote is part of the text, not the end of the string.
Example 2: New line
// \n creates a new line.
let text = "Line 1\nLine 2";
// Print the text.
console.log(text);
// Output:
// Line 1
// Line 2
Explanation:
The escape character \n moves the text after it to a new line.
8.3 Template Literals
Template literals use backticks instead of normal quotes.
They allow you to place variables directly inside strings using ${}.
They also make long strings and multi-line strings easier to write.
Example 1: Insert variable into string
// Store a name.
let name = "Sara";
// Use template literal with ${}.
let greeting = `Hello, ${name}!`;
// Print the greeting.
console.log(greeting);
// Output:
// Hello, Sara!
Explanation:
The value of name is inserted directly into the string.
Example 2: Multi-line string
// Backticks allow multi-line text.
let lesson = `Chapter 8
Strings
JavaScript Course`;
// Print the lesson.
console.log(lesson);
// Output:
// Chapter 8
// Strings
// JavaScript Course
Explanation:
Template literals keep the line breaks exactly as you write them.
8.4 String Methods
String methods are built-in tools that help you work with text.
You can change text to uppercase, lowercase, find length, slice parts, and more.
Methods are written after the string using a dot.
Example 1: Uppercase and lowercase
// Store text.
let word = "JavaScript";
// Convert to uppercase.
console.log(word.toUpperCase());
// Convert to lowercase.
console.log(word.toLowerCase());
// Output:
// JAVASCRIPT
// javascript
Explanation:
toUpperCase() makes letters capital. toLowerCase() makes letters small.
Example 2: String length
// Store a word.
let city = "Toronto";
// Count characters.
console.log(city.length);
// Output:
// 7
Explanation:
The length property counts how many characters are inside the string.
8.5 Searching
Searching means finding text inside another string.
JavaScript gives methods like includes(), indexOf(), and startsWith().
These are useful for search bars, filters, validation, and checking user input.
Example 1: includes()
// Store a sentence.
let sentence = "I am learning JavaScript";
// Check if the sentence contains JavaScript.
console.log(sentence.includes("JavaScript"));
// Output:
// true
Explanation:
includes() returns true because the word JavaScript exists inside the sentence.
Example 2: indexOf()
// Store text.
let text = "Hello world";
// Find the position of world.
console.log(text.indexOf("world"));
// Output:
// 6
Explanation:
indexOf() returns the starting position of the word. JavaScript starts counting from 0.
8.6 Replacing
Replacing means changing one part of a string into another value.
JavaScript provides replace() and replaceAll().
This is useful for correcting text, updating messages, cleaning input, and formatting content.
Example 1: replace()
// Store text.
let message = "I like HTML";
// Replace HTML with JavaScript.
let newMessage = message.replace("HTML", "JavaScript");
// Print the new message.
console.log(newMessage);
// Output:
// I like JavaScript
Explanation:
replace() finds the first matching text and changes it.
Example 2: replaceAll()
// Store repeated text.
let text = "apple apple apple";
// Replace all apples with oranges.
let result = text.replaceAll("apple", "orange");
// Print result.
console.log(result);
// Output:
// orange orange orange
Explanation:
replaceAll() changes every matching word in the string.
8.7 Splitting
Splitting means cutting a string into smaller parts.
The split() method turns a string into an array.
This is useful for names, emails, tags, sentences, CSV data, and user input.
Example 1: Split sentence into words
// Store a sentence.
let sentence = "I love JavaScript";
// Split by spaces.
let words = sentence.split(" ");
// Print array.
console.log(words);
// Output:
// ["I", "love", "JavaScript"]
Explanation:
The string is divided wherever JavaScript finds a space.
Example 2: Split CSV text
// Store comma-separated values.
let colors = "red,blue,green";
// Split by comma.
let colorList = colors.split(",");
// Print array.
console.log(colorList);
// Output:
// ["red", "blue", "green"]
Explanation:
This is common when reading data separated by commas.
8.8 Trimming
Trimming means removing extra spaces from the beginning or end of a string.
User input often contains accidental spaces.
The trim() method helps clean the text before saving, comparing, or displaying it.
Example 1: trim()
// Text has extra spaces.
let username = " Majid ";
// Remove spaces from both sides.
let cleanName = username.trim();
// Print clean value.
console.log(cleanName);
// Output:
// Majid
Explanation:
trim() removes spaces from the start and end, but not spaces in the middle.
Example 2: trimStart() and trimEnd()
// Text has spaces.
let text = " Hello ";
console.log(text.trimStart());
console.log(text.trimEnd());
// Output:
// Hello
// Hello
Explanation:
trimStart() removes spaces from the beginning. trimEnd() removes spaces from the end.
8.9 Unicode
Unicode allows JavaScript strings to support many languages, symbols, and emojis.
This is important because websites are used by people around the world.
Unicode helps display characters from English, Persian, French, Arabic, Chinese, and many other languages.
Example 1: Different languages
// Store text in different languages.
let english = "Hello";
let french = "Bonjour";
let persian = "سلام";
// Print all values.
console.log(english);
console.log(french);
console.log(persian);
// Output:
// Hello
// Bonjour
// سلام
Explanation:
JavaScript strings can store text from many languages because of Unicode support.
Example 2: Emoji in string
// Store emoji inside a string.
let message = "Great job! 🎉";
// Print the message.
console.log(message);
// Output:
// Great job! 🎉
Explanation:
Emojis are also Unicode characters, so JavaScript can store them in strings.
8.10 String Performance
String performance means writing string code that runs efficiently.
Small strings are easy, but very large text or repeated changes can slow programs.
For beginners, the best habit is to write clear code and use methods like join() when combining many pieces of text.
Example 1: Simple string joining
// Store parts of a message.
let first = "Hello";
let second = "JavaScript";
// Join strings.
let result = first + " " + second;
// Print result.
console.log(result);
// Output:
// Hello JavaScript
Explanation:
The plus sign is okay for joining a small number of strings.
Example 2: Use join() for many strings
// Store many words in an array.
let words = ["I", "am", "learning", "JavaScript"];
// Join them with spaces.
let sentence = words.join(" ");
// Print sentence.
console.log(sentence);
// Output:
// I am learning JavaScript
Explanation:
join() is clean and useful when combining many string parts from an array.
Chapter 8 Summary
- Strings store text values in JavaScript.
- Strings can be created with double quotes, single quotes, or backticks.
- Escape characters allow special characters inside strings.
- Template literals make it easy to insert variables into strings.
- String methods help change, search, replace, split, and clean text.
- Unicode lets JavaScript support many languages and emojis.
- Good string performance matters when working with large text or many text changes.