Ad – 728Γ—90
🌱 Beginner

JavaScript Strings – Complete Guide to String Manipulation

Strings are one of the most used data types in JavaScript β€” every text you display, every URL you build, every message you format involves strings. JavaScript provides an extensive set of string methods that make text manipulation powerful and expressive. This lesson covers string creation, template literals, all the essential methods, escape characters, and the important concept of string immutability.

⏱️ 26 min read 🎯 Beginner πŸ“… Updated 2026

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.

JavaScript
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);
β–Ά Output
It's a great day! He said "Hello!"

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.

JavaScript
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);
β–Ά Output
Hello, Alice! You are 30 years old. Next year you'll be 31. Is adult: yes Roses are red, Violets are blue, JavaScript is awesome, And so are you!

Escape Characters

Escape sequences let you include special characters inside strings using a backslash \.

EscapeCharacter
\'Single quote
\"Double quote
\\Backslash
\nNewline
\tTab
\rCarriage return
\u{1F600}Unicode emoji (ES6)
Ad – 336Γ—280

String Properties – length

The length property returns the number of characters in a string.

JavaScript
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"
β–Ά Output
10 0 7 J t S

Search Methods

JavaScript
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
β–Ά Output
true false true true true 31 31 -1 2 43

Transformation Methods

JavaScript
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---"
β–Ά Output
HELLO, WORLD! hello, world! Hello, World! Hello, World! Hello, World! I like dogs and cats like me I like dogs and dogs like me hahaha 0005 5---

Extracting Substrings

JavaScript
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"]
β–Ά Output
Java Script Script Scri Java Script ["Alice", "Bob", "Charlie", "Dave"] ["h", "e", "l", "l", "o"]
πŸ’‘
Prefer slice() over substring()

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.

ℹ️
Strings are Immutable

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

  1. Create a template literal that embeds your name, the current year (new Date().getFullYear()), and a calculated value like 2 ** 10.
  2. Take the string " hello world " and chain .trim(), .toUpperCase(), and .replace("WORLD", "JS") to produce "HELLO JS".
  3. Split the string "one:two:three:four" by ":" to get an array, then join it back with " - ".
  4. Use padStart() to format the numbers 1 through 5 as "001", "002", etc.
  5. 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.
  • length gives the character count; use bracket notation or charAt() 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() and substring()?
  • 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() and replaceAll()?

Frequently Asked Questions

How do I reverse a string in JavaScript? +

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("").

How do I check if a string contains only digits? +

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.).

What is the difference between charAt() and bracket notation? +

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.

How do I compare two strings alphabetically? +

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.

How do I convert a string to an array of words? +

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.