String Basics
Strings represent text. You can use single quotes, double quotes, or backticks.
const single = 'Hello';
const double = "World";
const template = `Hello, ${double}!`;
console.log(template); // Hello, World!
Try it Yourself →
Accessing Characters and Length
Use bracket notation or charAt to access characters. The length property gives the string size.
const text = "JavaScript";
console.log(text[0]); // J
console.log(text.charAt(4)); // S
console.log(text.length); // 10
Try it Yourself →
Changing Case
toUpperCase and toLowerCase transform the entire string.
const word = "Hello World";
console.log(word.toUpperCase()); // HELLO WORLD
console.log(word.toLowerCase()); // hello world
Try it Yourself →
Searching Within Strings
Use indexOf, includes, startsWith, and endsWith to search.
const sentence = "The quick brown fox";
console.log(sentence.includes("fox")); // true
console.log(sentence.startsWith("The")); // true
console.log(sentence.endsWith("fox")); // true
console.log(sentence.indexOf("brown")); // 10
Try it Yourself →
Extracting Substrings
slice, substring, and substr extract parts of a string. slice is the most flexible.
const str = "JavaScript";
console.log(str.slice(0, 4)); // Java
console.log(str.slice(4)); // Script
console.log(str.slice(-6)); // Script (negative index)
Try it Yourself →
Replacing Content
replace replaces the first match. replaceAll replaces all matches.
const phrase = "I like cats. Cats are cute.";
console.log(phrase.replace("cats", "dogs")); // I like dogs. Cats are cute.
console.log(phrase.replaceAll("cats", "dogs")); // I like dogs. Cats are cute.
console.log(phrase.replaceAll(/cats/gi, "dogs")); // I like dogs. Dogs are cute.
Try it Yourself →
Splitting and Joining
split breaks a string into an array. join does the reverse.
const csv = "apple,banana,cherry";
const fruits = csv.split(",");
console.log(fruits); // ["apple", "banana", "cherry"]
const list = fruits.join(" | ");
console.log(list); // apple | banana | cherry
Try it Yourself →
Trimming and Padding
trim removes whitespace. padStart and padEnd add padding.
const messy = " spaced out ";
console.log(messy.trim()); // "spaced out"
const id = "42";
console.log(id.padStart(5, "0")); // "00042"
console.log(id.padEnd(5, "X")); // "42XXX"
Try it Yourself →