Strings are one of the most common data types you'll work with in JavaScript. Whether you're displaying messages to users, processing form input, or manipulating text data, you'll need to know how to work with strings effectively. Let's explore modern string syntax and powerful built-in methods!
String Basics Review
Strings represent text and can be created three ways: single quotes, double quotes, or backticks (template literals).
// Three ways to create strings
let single = 'Hello';
let double = "Hello";
let template = `Hello`;
// All three work the same for simple strings
console.log(single); // Hello
console.log(double); // Hello
console.log(template); // HelloStrings Are Immutable
Once created, strings cannot be changed. String methods return new strings instead of modifying the original.
let message = "Hello";
// This doesn't change the original string
message.toUpperCase();
console.log(message); // Still "Hello"
// You must save the result to use it
let upperMessage = message.toUpperCase();
console.log(upperMessage); // "HELLO"
// Or reassign
message = message.toUpperCase();
console.log(message); // "HELLO"Template Literals (Backticks)
Template literals are the modern way to work with strings. They use backticks (`) and provide powerful features like variable interpolation and multi-line strings.
Variable Interpolation
Embed variables and expressions directly in strings using ${} syntax.
let name = "Alice";
let age = 25;
// Old way (concatenation)
let message1 = "Hello, my name is " + name + " and I'm " + age + " years old.";
// Modern way (template literal)
let message2 = `Hello, my name is ${name} and I'm ${age} years old.`;
console.log(message1); // Hello, my name is Alice and I'm 25 years old.
console.log(message2); // Hello, my name is Alice and I'm 25 years old.Expression Interpolation
You can put any JavaScript expression inside ${}.
let price = 50;
let quantity = 3;
// Calculations inside template literals
let total = `Total: $${price * quantity}`;
console.log(total); // Total: $150
// Function calls
let greeting = `Hello, ${name.toUpperCase()}!`;
console.log(greeting); // Hello, ALICE!
// Conditional expressions
let age = 20;
let status = `You are ${age >= 18 ? 'an adult' : 'a minor'}`;
console.log(status); // You are an adultMulti-Line Strings
Template literals preserve line breaks, making multi-line strings easy.
// Old way (needs \n)
let oldPoem = "Roses are red\nViolets are blue\nJavaScript is awesome\nAnd so are you";
// Modern way (natural line breaks)
let newPoem = `
Roses are red
Violets are blue
JavaScript is awesome
And so are you
`;
console.log(newPoem);See how template literals simplify string creation
Concatenation (Old)
// Old concatenation
let firstName = "John";
let lastName = "Doe";
let age = 30;
let city = "New York";
let profile = "Name: " + firstName + " " + lastName + "\n" +
"Age: " + age + "\n" +
"City: " + city;
console.log(profile);Template Literal (Modern)
// Modern template literal
let firstName = "John";
let lastName = "Doe";
let age = 30;
let city = "New York";
let profile = `Name: ${firstName} ${lastName}
Age: ${age}
City: ${city}`;
console.log(profile);Template Literals Practice
Experiment with modern string syntax
console.log() to see your output in the console above.String Properties
length Property
The length property returns the number of characters in a string.
let message = "Hello, World!";
console.log(message.length); // 13
let empty = "";
console.log(empty.length); // 0
let spaces = " ";
console.log(spaces.length); // 3 (spaces count!)
// Useful for validation
let password = "abc123";
if (password.length < 8) {
console.log("Password too short! Minimum 8 characters.");
}Accessing Individual Characters
let text = "JavaScript";
// Using bracket notation (like arrays)
console.log(text[0]); // J
console.log(text[4]); // S
console.log(text[9]); // t
// Using charAt() method
console.log(text.charAt(0)); // J
console.log(text.charAt(4)); // S
// Out of bounds
console.log(text[100]); // undefined
console.log(text.charAt(100)); // "" (empty string)
// Last character
let lastIndex = text.length - 1;
console.log(text[lastIndex]); // tCase Conversion Methods
let text = "Hello World";
// Convert to uppercase
console.log(text.toUpperCase()); // HELLO WORLD
// Convert to lowercase
console.log(text.toLowerCase()); // hello world
// Original string unchanged
console.log(text); // Hello World
// Common use: case-insensitive comparison
let input = "JAVASCRIPT";
let target = "javascript";
if (input.toLowerCase() === target.toLowerCase()) {
console.log("Match!"); // This will execute
}Practical Use Cases
// Email validation (emails are case-insensitive)
let email = "User@Example.COM";
let normalizedEmail = email.toLowerCase();
console.log(normalizedEmail); // user@example.com
// Display names
let firstName = "john";
let capitalized = firstName.charAt(0).toUpperCase() + firstName.slice(1);
console.log(capitalized); // John
// Acronyms
let title = "hypertext markup language";
let acronym = title.split(" ")
.map(word => word[0].toUpperCase())
.join("");
console.log(acronym); // HTMLSearching and Checking Strings
includes() - Check if String Contains Substring
let message = "JavaScript is awesome!";
// Check if string contains a word
console.log(message.includes("JavaScript")); // true
console.log(message.includes("Python")); // false
// Case-sensitive!
console.log(message.includes("javascript")); // false
// Case-insensitive check
let search = "AWESOME";
console.log(message.toLowerCase().includes(search.toLowerCase())); // true
// Practical use
let comment = "This is spam and fake";
if (comment.includes("spam") || comment.includes("fake")) {
console.log("Comment flagged!");
}startsWith() and endsWith()
let filename = "document.pdf";
// Check how string starts
console.log(filename.startsWith("doc")); // true
console.log(filename.startsWith("Doc")); // false
// Check how string ends
console.log(filename.endsWith(".pdf")); // true
console.log(filename.endsWith(".txt")); // false
// Practical: file type validation
if (filename.endsWith(".pdf") || filename.endsWith(".doc")) {
console.log("Valid document format");
}
// URL validation
let url = "https://example.com";
if (url.startsWith("https://")) {
console.log("Secure URL");
}indexOf() and lastIndexOf()
let text = "Hello World, Hello Universe";
// Find first occurrence
console.log(text.indexOf("Hello")); // 0
console.log(text.indexOf("World")); // 6
console.log(text.indexOf("Goodbye")); // -1 (not found)
// Find last occurrence
console.log(text.lastIndexOf("Hello")); // 13
// Check if substring exists
if (text.indexOf("World") !== -1) {
console.log("Found 'World'");
}
// Modern alternative (cleaner)
if (text.includes("World")) {
console.log("Found 'World'");
}Extracting Parts of Strings
slice() - Extract a Section
let text = "JavaScript";
// slice(start, end)
console.log(text.slice(0, 4)); // Java
console.log(text.slice(4)); // Script (from 4 to end)
console.log(text.slice(4, 10)); // Script
// Negative indices (count from end)
console.log(text.slice(-6)); // Script (last 6 characters)
console.log(text.slice(-6, -2)); // Scri
// Get last 3 characters
console.log(text.slice(-3)); // iptsubstring() - Similar to slice
let text = "JavaScript";
// substring(start, end)
console.log(text.substring(0, 4)); // Java
console.log(text.substring(4)); // Script
// Note: substring doesn't support negative indices
console.log(text.substring(-3)); // JavaScript (treats -3 as 0)
// slice is generally preferred over substringPractical Examples
// Extract domain from email
let email = "user@example.com";
let atIndex = email.indexOf("@");
let domain = email.slice(atIndex + 1);
console.log(domain); // example.com
// Get file extension
let filename = "document.pdf";
let dotIndex = filename.lastIndexOf(".");
let extension = filename.slice(dotIndex);
console.log(extension); // .pdf
// Truncate long text
let longText = "This is a very long text that needs to be shortened";
let preview = longText.slice(0, 20) + "...";
console.log(preview); // This is a very long...Modifying Strings
trim(), trimStart(), trimEnd()
let text = " Hello World ";
// Remove whitespace from both ends
console.log(text.trim()); // "Hello World"
// Remove from start only
console.log(text.trimStart()); // "Hello World "
// Remove from end only
console.log(text.trimEnd()); // " Hello World"
// Practical: clean user input
let userInput = " john@example.com ";
let cleanEmail = userInput.trim().toLowerCase();
console.log(cleanEmail); // "john@example.com"replace() and replaceAll()
let text = "Hello World, Hello Universe";
// Replace first occurrence
console.log(text.replace("Hello", "Hi")); // Hi World, Hello Universe
// Replace all occurrences (ES2021)
console.log(text.replaceAll("Hello", "Hi")); // Hi World, Hi Universe
// Case-insensitive replace with regex
let message = "JavaScript is GREAT! JavaScript rocks!";
let newMessage = message.replace(/javascript/gi, "JS");
console.log(newMessage); // JS is GREAT! JS rocks!
// Practical: clean up text
let dirty = "This has extra spaces";
let clean = dirty.replace(/\s+/g, " ");
console.log(clean); // This has extra spacesrepeat()
let star = "*";
// Repeat a string
console.log(star.repeat(5)); // *****
// Create patterns
let line = "-".repeat(20);
console.log(line); // --------------------
// Indentation
let indent = " ".repeat(4);
console.log(indent + "Indented text");
// Loading indicator
for (let i = 1; i <= 3; i++) {
console.log("Loading" + ".".repeat(i));
}
// Loading.
// Loading..
// Loading...Splitting and Joining Strings
split() - String to Array
let sentence = "JavaScript is awesome";
// Split into words
let words = sentence.split(" ");
console.log(words); // ["JavaScript", "is", "awesome"]
// Split into characters
let text = "Hello";
let chars = text.split("");
console.log(chars); // ["H", "e", "l", "l", "o"]
// Split by comma
let csv = "apple,banana,orange";
let fruits = csv.split(",");
console.log(fruits); // ["apple", "banana", "orange"]
// Limit number of splits
let limited = sentence.split(" ", 2);
console.log(limited); // ["JavaScript", "is"]join() - Array to String
let words = ["JavaScript", "is", "awesome"];
// Join with space
console.log(words.join(" ")); // JavaScript is awesome
// Join with comma
console.log(words.join(",")); // JavaScript,is,awesome
// Join with nothing
console.log(words.join("")); // JavaScriptisawesome
// Join with custom separator
console.log(words.join(" - ")); // JavaScript - is - awesomePractical Examples
// Reverse a string
let text = "JavaScript";
let reversed = text.split("").reverse().join("");
console.log(reversed); // tpircSavaJ
// Count words
let sentence = "The quick brown fox jumps";
let wordCount = sentence.split(" ").length;
console.log(wordCount); // 5
// Create initials
let fullName = "John Michael Doe";
let initials = fullName
.split(" ")
.map(word => word[0])
.join("");
console.log(initials); // JMD
// Format phone number
let digits = "1234567890";
let formatted = digits.split("").join("-");
console.log(formatted); // 1-2-3-4-5-6-7-8-9-0
// Better phone format
let phone = "1234567890";
let parts = [phone.slice(0,3), phone.slice(3,6), phone.slice(6)];
console.log(parts.join("-")); // 123-456-7890Practical String Examples
Example 1: Input Validation
function validateUsername(username) {
// Remove whitespace
username = username.trim();
// Check length
if (username.length < 3) {
return "Username too short (minimum 3 characters)";
}
if (username.length > 20) {
return "Username too long (maximum 20 characters)";
}
// Check for spaces
if (username.includes(" ")) {
return "Username cannot contain spaces";
}
// Check for special characters (simple check)
if (!/^[a-zA-Z0-9_]+$/.test(username)) {
return "Username can only contain letters, numbers, and underscores";
}
return "Valid username!";
}
console.log(validateUsername(" john_doe ")); // Valid username!
console.log(validateUsername("ab")); // Username too short
console.log(validateUsername("john doe")); // Username cannot contain spacesExample 2: Text Formatting
function formatName(firstName, lastName) {
// Clean and capitalize
let first = firstName.trim().toLowerCase();
let last = lastName.trim().toLowerCase();
// Capitalize first letter
first = first.charAt(0).toUpperCase() + first.slice(1);
last = last.charAt(0).toUpperCase() + last.slice(1);
return `${first} ${last}`;
}
console.log(formatName(" jOHN ", " dOE ")); // John Doe
function createSlug(title) {
return title
.toLowerCase()
.trim()
.replace(/\s+/g, "-") // Replace spaces with hyphens
.replace(/[^a-z0-9-]/g, "") // Remove special characters
.replace(/-+/g, "-"); // Replace multiple hyphens with single
}
console.log(createSlug("Hello World! How are you?")); // hello-world-how-are-youExample 3: Data Extraction
function parseEmail(email) {
email = email.trim().toLowerCase();
let atIndex = email.indexOf("@");
if (atIndex === -1) {
return { valid: false };
}
let username = email.slice(0, atIndex);
let domain = email.slice(atIndex + 1);
return {
valid: true,
username: username,
domain: domain,
fullEmail: email
};
}
let result = parseEmail(" John.Doe@Example.COM ");
console.log(result);
// {
// valid: true,
// username: "john.doe",
// domain: "example.com",
// fullEmail: "john.doe@example.com"
// }Text Processing Tool
See multiple string methods in action
console.log() to see your output in the console above.Method Chaining
Since string methods return new strings, you can chain multiple methods together.
let input = " HELLO WORLD ";
// Chain multiple methods
let result = input
.trim() // "HELLO WORLD"
.toLowerCase() // "hello world"
.replace(" ", "-"); // "hello-world"
console.log(result); // hello-world
// More complex chaining
let email = " User@EXAMPLE.com ";
let normalized = email.trim().toLowerCase();
console.log(normalized); // user@example.com
// Processing user input
let userInput = " JavaScript is AWESOME! ";
let processed = userInput
.trim()
.replace(/\s+/g, " ") // Normalize spaces
.toLowerCase()
.split(" ")
.join("-");
console.log(processed); // javascript-is-awesome!Key Takeaways
- Use template literals (
`) for modern string creation - Embed variables with
${}syntax - Strings are immutable—methods return new strings
lengthproperty gives character counttoUpperCase()andtoLowerCase()convert caseincludes(),startsWith(),endsWith()for searchingslice()extracts parts of stringstrim()removes whitespace from endsreplace()andreplaceAll()substitute textsplit()converts string to array- Chain methods together for complex operations
- Always clean and validate user input
What's Next?
You now have a solid understanding of how to work with strings in JavaScript! String manipulation is a fundamental skill you'll use constantly—from form validation to data processing to building user interfaces.
In the next lesson, we'll explore Type Conversion and Coercion—learning how JavaScript converts between different data types, both explicitly (when you tell it to) and implicitly (when it happens automatically). Understanding this will help you avoid common bugs and write more predictable code.
💪 Practice Challenge:
Before moving on, try building:
- A function that takes a full name and returns initials
- A password validator (minimum length, must contain uppercase, lowercase, and number)
- A function that creates a URL slug from a title (lowercase, hyphens instead of spaces)
- A text truncator that adds "..." if text exceeds a certain length
- An email masker that shows only first 3 characters before @ (j***@example.com)