Creating Strings
JavaScript strings can be created with single quotes, double quotes, or backticks (template literals). All three create string primitives β use whichever you prefer consistently, but reserve backticks for when you need expressions or multiline.
let single = 'Hello, World!';
let double = "Hello, World!";
let template = `Hello, World!`;
// Mixing quotes to avoid escaping
let msg1 = "It's a great day!"; // single quote inside double
let msg2 = 'He said "Hello!"'; // double quote inside single
let msg3 = `He said "It's fine!"`; // both inside backtick
console.log(msg1);
console.log(msg2);
Template Literals
Template literals (backtick strings) support expression interpolation with ${} and can span multiple lines without escape characters. They are a major improvement over string concatenation.
const name = "Alice";
const age = 30;
// Expression interpolation
console.log(`Hello, ${name}! You are ${age} years old.`);
console.log(`Next year you'll be ${age + 1}.`);
console.log(`Is adult: ${age >= 18 ? "yes" : "no"}`);
// Multiline strings
const poem = `Roses are red,
Violets are blue,
JavaScript is awesome,
And so are you!`;
console.log(poem);
Escape Characters
Escape sequences let you include special characters inside strings using a backslash \.
| Escape | Character |
|---|---|
\' | Single quote |
\" | Double quote |
\\ | Backslash |
\n | Newline |
\t | Tab |
\r | Carriage return |
\u{1F600} | Unicode emoji (ES6) |
String Properties β length
The length property returns the number of characters in a string.
const str = "JavaScript";
console.log(str.length); // 10
console.log("".length); // 0
console.log(" hello ".length); // 7 (spaces count!)
// Accessing individual characters (0-indexed)
console.log(str[0]); // "J"
console.log(str[str.length - 1]); // "t" β last character
console.log(str.charAt(4)); // "S"
Search Methods
const text = "The quick brown fox jumps over the lazy dog";
// includes β returns true/false
console.log(text.includes("fox")); // true
console.log(text.includes("cat")); // false
// startsWith / endsWith
console.log(text.startsWith("The")); // true
console.log(text.endsWith("dog")); // true
console.log(text.startsWith("quick", 4)); // true (start from index 4)
// indexOf / lastIndexOf β returns index or -1
console.log(text.indexOf("the")); // 31
console.log(text.lastIndexOf("the")); // 31
console.log(text.indexOf("cat")); // -1
console.log(text.indexOf("e")); // 2
console.log(text.lastIndexOf("e")); // 43
Transformation Methods
let str = " Hello, World! ";
// Case conversion
console.log(str.toUpperCase()); // " HELLO, WORLD! "
console.log(str.toLowerCase()); // " hello, world! "
// Trimming whitespace
console.log(str.trim()); // "Hello, World!"
console.log(str.trimStart()); // "Hello, World! "
console.log(str.trimEnd()); // " Hello, World!"
// Replacing
const s = "I like cats and cats like me";
console.log(s.replace("cats", "dogs")); // replaces first only
console.log(s.replaceAll("cats", "dogs")); // replaces all
// repeat, padStart, padEnd
console.log("ha".repeat(3)); // "hahaha"
console.log("5".padStart(4, "0")); // "0005" (useful for formatting)
console.log("5".padEnd(4, "-")); // "5---"
Extracting Substrings
const str = "JavaScript";
// 0123456789
// slice(start, end) β end is exclusive; negative counts from end
console.log(str.slice(0, 4)); // "Java"
console.log(str.slice(4)); // "Script"
console.log(str.slice(-6)); // "Script" (last 6 chars)
console.log(str.slice(4, 8)); // "Scri"
// substring(start, end) β similar to slice, but no negative indices
console.log(str.substring(0, 4)); // "Java"
console.log(str.substring(4)); // "Script"
// split β convert string to array
const csv = "Alice,Bob,Charlie,Dave";
const names = csv.split(",");
console.log(names); // ["Alice", "Bob", "Charlie", "Dave"]
console.log("hello".split("")); // ["h","e","l","l","o"]
slice() supports negative indices (counting from the end), making it more flexible. substring() treats negative arguments as 0. In modern JavaScript, slice() is the preferred choice.
Every string method returns a new string β it never modifies the original. str.toUpperCase() returns a new uppercase string; str is unchanged. Always capture the result: const upper = str.toUpperCase();
ποΈ Practical Exercise
- Create a template literal that embeds your name, the current year (
new Date().getFullYear()), and a calculated value like2 ** 10. - Take the string
" hello world "and chain.trim(),.toUpperCase(), and.replace("WORLD", "JS")to produce"HELLO JS". - Split the string
"one:two:three:four"by":"to get an array, then join it back with" - ". - Use
padStart()to format the numbers 1 through 5 as"001","002", etc. - Write a function that takes a full name string and returns the initials (e.g.,
"Alice Smith"β"A.S.").
π₯ Challenge Exercise
Write a function slugify(title) that converts a blog post title into a URL slug. For example, "Hello World! This is JavaScript." should return "hello-world-this-is-javascript". You'll need to: convert to lowercase, trim whitespace, remove punctuation (use replace(/[^\w\s]/g, "")), and replace spaces with hyphens using replaceAll() or split/join.
π Summary
- Template literals (backticks) support
${expression}interpolation and multiline strings. lengthgives the character count; use bracket notation orcharAt()to access individual characters.- Search methods:
includes(),startsWith(),endsWith(),indexOf(),lastIndexOf(). - Transform methods:
toUpperCase(),toLowerCase(),trim(),replace(),replaceAll(),repeat(),padStart(),padEnd(). - Extract methods:
slice()(preferred),substring(),split(). - Strings are immutable β all methods return new strings, never modifying the original.
Interview Questions
- What is the difference between
slice()andsubstring()? - How do template literals differ from regular strings?
- What does it mean that strings are immutable?
- How would you reverse a string in JavaScript?
- What is the difference between
replace()andreplaceAll()?
Frequently Asked Questions
The standard trick: str.split("").reverse().join(""). This splits the string into an array of characters, reverses the array, and joins them back. Note this doesn't correctly handle multi-character Unicode characters (emoji, some accented letters). For production use, consider a library or Array.from(str).reverse().join("").
Use a regular expression: /^\d+$/.test(str). This returns true if every character is a digit 0β9. Alternatively, !isNaN(str) && str.trim() !== "" checks if the string can be converted to a valid number, but it's less precise (accepts spaces, decimal points, etc.).
Both return the character at a given index. str[i] returns undefined for out-of-range indices; str.charAt(i) returns an empty string "". In modern JavaScript, bracket notation is more commonly used and shorter.
Use === for equality. For ordering, use str1.localeCompare(str2) β it returns a negative number if str1 comes first, positive if str2 comes first, or 0 if equal. This is the correct way to sort strings, especially for non-ASCII characters. The < and > operators work but compare by Unicode code points, not locale.
Use str.trim().split(/\s+/) β splitting on one or more whitespace characters handles multiple spaces and tabs: "hello world".trim().split(/\s+/) gives ["hello", "world"]. A simple split(" ") would produce empty strings for consecutive spaces.