JavaScript — Strings
What are Strings?
Strings represent text data — sequences of characters wrapped in quotes:
const name = "Alice";
const greeting = 'Hello, World!';
const template = `Welcome, ${name}!`;
Three Ways to Create Strings
// Double quotes
const a = "Hello";
// Single quotes
const b = 'Hello';
// Template literals (backticks)
const c = `Hello`;
Template literals are the most powerful — they support expressions and multi-line:
const name = "Alice";
const age = 25;
// Expression embedding
const message = `Hello, ${name}. You are ${age} years old.`;
// Multi-line
const html = `
<div>
<h1>${name}</h1>
<p>Age: ${age}</p>
</div>
`;
// Expressions in template literals
const price = 9.99;
const total = `Total: $${(price * 1.1).toFixed(2)}`;
String Length
const name = "Hello";
name.length; // 5
"".length; // 0
Accessing Characters
const str = "Hello";
str[0]; // "H"
str[1]; // "e"
str.at(-1); // "o" — last character
str.at(-2); // "l" — second to last
String Methods
Case Methods
"hello".toUpperCase(); // "HELLO"
"HELLO".toLowerCase(); // "hello"
"hello world".charAt(0).toUpperCase() + "ello world"; // "Hello world"
Searching
const str = "Hello, World!";
str.includes("World"); // true
str.startsWith("Hello"); // true
str.endsWith("!"); // true
str.indexOf("World"); // 7
str.lastIndexOf("l"); // 10
str.search(/World/); // 7
Extracting
const str = "Hello, World!";
str.slice(0, 5); // "Hello"
str.slice(7); // "World!"
str.substring(0, 5); // "Hello" (similar to slice)
str.substr(7, 5); // "World" (deprecated — avoid)
Modifying
const str = "Hello, World!";
str.replace("World", "JavaScript"); // "Hello, JavaScript!"
str.replaceAll("l", "L"); // "HeLLo, WorLd!"
str.trim(); // removes leading/trailing spaces
str.padStart(20, "-"); // "--------Hello, World!"
str.padEnd(20, "-"); // "Hello, World!--------"
Splitting and Joining
// String to array
"hello world".split(" "); // ["hello", "world"]
"a,b,c".split(","); // ["a", "b", "c"]
"hello".split(""); // ["h", "e", "l", "l", "o"]
// Array to string
["a", "b", "c"].join("-"); // "a-b-c"
["Hello", "World"].join(" "); // "Hello World"
Template Literal Expressions
// Function calls
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
const name = `alice`;
const result = `${capitalize(name)} is here`; // "Alice is here"
// Ternary in template
const age = 20;
const status = `You are ${age >= 18 ? "an adult" : "a minor"}`;
// Nested templates
const items = ["apple", "banana", "cherry"];
const list = `<ul>${items.map(item => `<li>${item}</li>`).join("")}</ul>`;
String Comparison
"apple" < "banana"; // true (alphabetical order)
"apple" === "Apple"; // false (case-sensitive)
"apple".localeCompare("banana"); // -1 (comes before)
Escape Characters
const str = "Hello\nWorld"; // newline
const str = "She said \"Hi\""; // escaped quotes
const str = 'It\'s a test'; // escaped apostrophe
const str = "Path: C:\\Users"; // escaped backslash
Common Patterns
// Check if string is empty
if (str.trim() === "") { /* empty */ }
// Capitalize first letter
const capitalize = s => s.charAt(0).toUpperCase() + s.slice(1);
// Truncate with ellipsis
function truncate(str, max) {
return str.length > max ? str.slice(0, max) + "..." : str;
}
// Count occurrences
function countChar(str, char) {
return str.split(char).length - 1;
}
countChar("hello world", "l"); // 3
Mini Practice
- Create a template literal that includes a variable and a math expression
- Reverse a string using
split,reverse, andjoin - Count how many times a letter appears in a sentence
- Capitalize every word in a string
- Check if a string is a palindrome
Up Next
Next: Numbers →
Related Topics
Frequently Asked Questions about Strings
What is Strings in JavaScript?
Strings is a fundamental concept in JavaScript. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Strings?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Strings.
Why is Strings important in JavaScript?
Strings is essential for JavaScript development. Understanding this concept will help you write better code and solve real-world problems more effectively.