Strings & String Methods

Reviewed & published by Brayan K

Usernames, search queries, file paths, JSON, URLs, messages — almost everything a program touches arrives as text. Mastering strings is mastering the most common job in real-world code: cleaning, slicing, searching, and reshaping words.

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

This lesson is your reference for the string methods you'll reach for every single day.

What You'll Learn in This Lesson

🧵 Real-World Analogy: A string is like a row of beads on a thread:

🧠 Creating Strings & Immutability

You can write strings with single quotes, double quotes, or backticks. Backtick strings (template literals) are special: they interpolate expressions and span multiple lines.

📏 Length & Accessing Characters

The .length property counts characters. Index with brackets or, for negative-from-the-end access, the modern .at() method.

🔍 Searching Inside Strings

Checking whether text contains, starts with, or ends with something is one of the most common tasks in form validation, routing, and filtering:

✂️ Extracting Substrings with slice

slice(start, end) copies characters from start up to (but not including) end. Negative numbers count from the end, which makes "grab the last few characters" trivial:

🔧 Transforming Strings

Casing, trimming whitespace, replacing, and padding cover most "clean this input up" jobs. Remember: each returns a new string.

🪓 split & join — Strings ↔ Arrays

split turns a string into an array; join turns an array back into a string. Together they power CSV parsing, word counting, and reformatting:

📋 String Method Cheat Sheet

MethodDoesExample → Result
includesContains substring?"cat".includes("a") → true
sliceExtract part"hello".slice(1, 3) → "el"
trimRemove edge spaces" hi ".trim() → "hi"
replaceAllSwap every match"a-b-c".replaceAll("-","/") → "a/b/c"
splitString → array"a,b".split(",") → ["a","b"]
padStartPad to length"5".padStart(2,"0") → "05"
const fullName = "  ada lovelace  ";

// Clean it up
const clean = fullName.trim();
console.log("Cleaned:", clean);

// Capitalize each word
const titleCase = clean
  .split(" ")
  .map((w) => w[0].toUpperCase() + w.slice(1))
  .join(" ");
console.log("Title case:", titleCase);

// Search
const email = "ada@math.org";
console.log("Has @:", email.includes("@"));
console.log("Domain:", email.slice(email.indexOf("@") + 1));

// Build an initials string
const initials = clean
  .split(" ")
  .map((w) => w[0].toUpperCase())
  .join("");
console.log("Initials:", initials);

// Reverse trick
console.log("Reversed:", "JavaScript".split("").reverse().join(""));

// Try it: write isPalindrome(str) using the reverse trick!

🧩 Reorder Challenge

These lines should take a raw filename and produce a clean uppercase extension. They are scrambled — reorder them so the final log is PDF.

B → D → A → C → E

Why: you need the raw string (B) before you can trim it (D). The dot position (A) must be found on the trimmed string, and slice(dot + 1) (C) depends on that index. Only then can you uppercase and print (E). Note: line A in the puzzle searched file but the fixed version searches trimmed — searching the untrimmed string would offset every index by the leading spaces.

🧠 Quick Recall

hi — strings are immutable, so the bracket assignment is silently ignored. To capitalize you'd need s = "H" + s.slice(1).

2. What is the result?

a+b-c — replace with a plain string only swaps the first match. Use replaceAll("-", "+") to get a+b+c.

3. What does this log?

2 — splitting on a single space produces ["hello", "world"], an array of length 2. This is the classic word-count pattern.

⚠️ Common Mistakes to Avoid

Lesson Complete — Strings & String Methods!

Practice quiz

Strings in JavaScript are immutable. What does word[0] = 'b' do to the string in word = 'cat'?

  • Changes it to 'bat'
  • Throws a TypeError
  • Silently does nothing; word stays 'cat'
  • Deletes the first character

Answer: Silently does nothing; word stays 'cat'. Strings are immutable, so bracket assignment is silently ignored in non-strict mode and word stays 'cat'.

What does 'Tokyo'.length log?

  • 4
  • 5
  • 6
  • 0

Answer: 5. 'Tokyo' has 5 characters, and .length counts characters.

What is the modern way to get the LAST character of a string?

  • str.last()
  • str.at(-1)
  • str.charAt(-1)
  • str.end()

Answer: str.at(-1). .at(-1) accepts negative indices and returns the last character; charAt does not accept negatives.

What does 'ada@example.com'.indexOf('example') return?

  • true
  • 0
  • 4
  • -1

Answer: 4. indexOf returns the starting position of the match; 'example' starts at index 4.

What does 'ada@example.com'.indexOf('zzz') return when the substring is not found?

  • 0
  • null
  • false
  • -1

Answer: -1. indexOf returns -1 when the substring is not found.

What does 'report-2024.pdf'.slice(-3) return?

  • 'pdf'
  • '.pdf'
  • '2024'
  • 'report'

Answer: 'pdf'. A negative argument counts from the end, so slice(-3) grabs the last 3 characters: 'pdf'.

What does '2024-1-5'.replace('-', '/') log?

  • '2024/1/5'
  • '2024/1-5'
  • '2024-1-5'
  • '2024-1/5'

Answer: '2024/1-5'. replace with a plain string only swaps the FIRST match, giving '2024/1-5'.

Which method swaps EVERY matching substring, turning '2024-1-5' into '2024/1/5'?

  • replace
  • replaceAll
  • split
  • slice

Answer: replaceAll. replaceAll replaces all matches, while replace only changes the first one.

What does '7'.padStart(3, '0') return?

  • '700'
  • '07'
  • '007'
  • '7'

Answer: '007'. padStart pads the start until the string reaches length 3, producing '007'.

What does 'hello'.split('').reverse().join('') log?

  • 'hello'
  • 'olleh'
  • 'h e l l o'
  • ['o','l','l','e','h']

Answer: 'olleh'. split('') makes a char array, reverse() flips it, and join('') glues it back into 'olleh'.

Continue this course

Frequently asked questions

Why does changing a character in a string not work?

Strings in JavaScript are immutable — every method that 'modifies' a string actually returns a brand-new string and leaves the original untouched. str[0] = 'X' silently does nothing in non-strict mode. To change text, build a new string with methods like slice, replace, or template literals and assign it back.

What's the difference between slice, substring, and substr?

slice(start, end) is the modern go-to and accepts negative indices to count from the end. substring(start, end) is similar but swaps the arguments if start is greater than end and treats negatives as 0. substr(start, length) is deprecated — avoid it. In new code, reach for slice.

When should I use includes vs indexOf?

Use includes('x') when you just need a yes/no answer about whether a substring is present — it returns a boolean and reads clearly. Use indexOf('x') when you actually need the position (it returns -1 if not found). Prefer includes for readability whenever you don't need the index.

How do I split a sentence into words and rejoin them?

Use split to break a string into an array on a delimiter — 'a,b,c'.split(',') gives ['a','b','c']. Use join to glue an array back into a string — ['a','b'].join('-') gives 'a-b'. split('') and join('') let you work character by character.

Why use template literals instead of + concatenation?

Template literals (backticks) let you embed expressions with ${} directly inside text, support multi-line strings without , and avoid the noisy, error-prone soup of quotes and plus signs. They are the modern default for building dynamic strings.