JavaScript Strings: Creation, Manipulation, Template Literals
Strings are sequences of characters. They’re one of the most commonly used data types in JavaScript.
Creating Strings
String Literals
const single = 'Hello';
const double = "World";
const backtick = `JavaScript`;
console.log(typeof single); // "string"
String Constructor
const str = new String("Hello");
console.log(typeof str); // "object" (not recommended)
Empty String
const empty = "";
console.log(empty.length); // 0
String Properties
length
Get string length:
const str = "Hello";
console.log(str.length); // 5
const emoji = "๐";
console.log(emoji.length); // 2 (some characters take 2 units)
Accessing Characters
const str = "Hello";
console.log(str[0]); // "H"
console.log(str[1]); // "e"
console.log(str[4]); // "o"
console.log(str[10]); // undefined
String Methods
Case Conversion
const str = "Hello World";
console.log(str.toUpperCase()); // "HELLO WORLD"
console.log(str.toLowerCase()); // "hello world"
console.log(str.toLocaleUpperCase()); // "HELLO WORLD"
console.log(str.toLocaleLowerCase()); // "hello world"
Trimming
const str = " Hello World ";
console.log(str.trim()); // "Hello World"
console.log(str.trimStart()); // "Hello World "
console.log(str.trimEnd()); // " Hello World"
Searching
const str = "Hello World";
console.log(str.indexOf("o")); // 4
console.log(str.lastIndexOf("o")); // 7
console.log(str.includes("World")); // true
console.log(str.startsWith("Hello")); // true
console.log(str.endsWith("World")); // true
Extracting Substrings
const str = "Hello World";
// slice(start, end)
console.log(str.slice(0, 5)); // "Hello"
console.log(str.slice(6)); // "World"
console.log(str.slice(-5)); // "World"
// substring(start, end) - similar to slice
console.log(str.substring(0, 5)); // "Hello"
// substr(start, length) - deprecated
console.log(str.substr(0, 5)); // "Hello"
Replacing
const str = "Hello World World";
// Replace first occurrence
console.log(str.replace("World", "JavaScript")); // "Hello JavaScript World"
// Replace all with regex
console.log(str.replace(/World/g, "JavaScript")); // "Hello JavaScript JavaScript"
// replaceAll (ES2021)
console.log(str.replaceAll("World", "JavaScript")); // "Hello JavaScript JavaScript"
Splitting
const str = "apple,banana,orange";
console.log(str.split(",")); // ["apple", "banana", "orange"]
console.log(str.split("")); // ["a", "p", "p", "l", "e", ...]
console.log(str.split(",", 2)); // ["apple", "banana"]
Repeating
const str = "Ha";
console.log(str.repeat(3)); // "HaHaHa"
console.log("*".repeat(5)); // "*****"
Padding
const str = "5";
console.log(str.padStart(3, "0")); // "005"
console.log(str.padEnd(3, "0")); // "500"
Concatenation
const str1 = "Hello";
const str2 = "World";
// Using +
console.log(str1 + " " + str2); // "Hello World"
// Using concat()
console.log(str1.concat(" ", str2)); // "Hello World"
// Using template literals (recommended)
console.log(`${str1} ${str2}`); // "Hello World"
Template Literals
Modern way to create strings with interpolation:
const name = "Alice";
const age = 30;
const message = `Hello, ${name}! You are ${age} years old.`;
console.log(message); // "Hello, Alice! You are 30 years old."
Multi-line Strings
const poem = `
Roses are red,
Violets are blue,
JavaScript is fun,
And so are you!
`;
console.log(poem);
Expressions in Templates
const a = 5;
const b = 10;
console.log(`${a} + ${b} = ${a + b}`); // "5 + 10 = 15"
console.log(`${a > b ? "a is greater" : "b is greater"}`); // "b is greater"
Tagged Templates
Advanced feature for custom processing:
function highlight(strings, ...values) {
let result = "";
for (let i = 0; i < strings.length; i++) {
result += strings[i];
if (i < values.length) {
result += `**${values[i]}**`;
}
}
return result;
}
const name = "Alice";
const age = 30;
console.log(highlight`Name: ${name}, Age: ${age}`);
// "Name: **Alice**, Age: **30**"
String Comparison
Equality
console.log("hello" === "hello"); // true
console.log("hello" === "Hello"); // false (case-sensitive)
console.log("hello" == "hello"); // true
Ordering
console.log("a" < "b"); // true
console.log("apple" < "banana"); // true
console.log("10" < "2"); // true (string comparison, not numeric)
localeCompare()
const str1 = "apple";
const str2 = "banana";
console.log(str1.localeCompare(str2)); // -1 (str1 comes first)
console.log(str2.localeCompare(str1)); // 1 (str2 comes first)
console.log(str1.localeCompare("apple")); // 0 (equal)
Practical Examples
Email Validation
function isValidEmail(email) {
return email.includes("@") && email.includes(".");
}
console.log(isValidEmail("[email protected]")); // true
console.log(isValidEmail("invalid.email")); // false
URL Slug Generation
function generateSlug(title) {
return title
.toLowerCase()
.trim()
.replace(/\s+/g, "-")
.replace(/[^\w-]/g, "");
}
console.log(generateSlug("Hello World!")); // "hello-world"
console.log(generateSlug("JavaScript Tips & Tricks")); // "javascript-tips-tricks"
Capitalize First Letter
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
console.log(capitalize("hello")); // "Hello"
console.log(capitalize("world")); // "World"
Reverse String
function reverseString(str) {
return str.split("").reverse().join("");
}
console.log(reverseString("hello")); // "olleh"
Count Occurrences
function countOccurrences(str, char) {
return str.split(char).length - 1;
}
console.log(countOccurrences("hello", "l")); // 2
console.log(countOccurrences("mississippi", "s")); // 4
Format Currency
function formatCurrency(amount) {
return `$${amount.toFixed(2)}`;
}
console.log(formatCurrency(10)); // "$10.00"
console.log(formatCurrency(10.5)); // "$10.50"
String Immutability
Strings are immutable - methods return new strings:
const original = "hello";
const uppercase = original.toUpperCase();
console.log(original); // "hello" (unchanged)
console.log(uppercase); // "HELLO"
Performance Tips
Use Template Literals
// Good - template literals
const name = "Alice";
const message = `Hello, ${name}!`;
// Avoid - multiple concatenations
const message2 = "Hello, " + name + "!";
Use join() for Multiple Concatenations
// Good - join for many strings
const parts = ["Hello", "World", "JavaScript"];
const result = parts.join(" ");
// Avoid - repeated concatenation
let result2 = "";
for (const part of parts) {
result2 += part + " ";
}
Summary
- Create: single quotes, double quotes, template literals
- Access: indexing with [index]
- Methods: toUpperCase, toLowerCase, trim, slice, split, replace
- Template literals:
${expression}for interpolation - Immutable: methods return new strings
- Performance: use template literals and join()
Related Resources
Official Documentation
Next Steps
- Regular Expressions in JavaScript
- Type Coercion and Type Conversion
- Array Methods: map, filter, reduce, forEach
Comments