Skip to content

Modern String Methods

This lesson explains Modern String Methods with clear examples, use cases, and best practices so you can use modern JavaScript confidently in real projects.

ES6+ Modern String Methods Overview

ES6 and later JavaScript versions added many useful string methods that make text processing cleaner and more expressive. These methods help with searching, padding, repeating, replacing, trimming, and accessing characters without writing custom helper functions.

Modern string methods are widely used in form validation, search filters, URL handling, formatting, logging, and UI text processing. They return new values instead of mutating the original string because strings are immutable in JavaScript.

Feature Description
Introduced Across ES6, ES2017, ES2020, ES2021, ES2022
Data Type Strings are immutable primitives
Search Methods includes(), startsWith(), endsWith()
Formatting Methods padStart(), padEnd(), repeat()
Access Methods at(), codePointAt()
Common Uses Validation, search, formatting, cleanup, parsing

Basic Modern String Methods Example

const email =
  "alex@example.com";

console.log(
  email.includes("@")
);

console.log(
  email.startsWith("alex")
);

console.log(
  email.endsWith(".com")
);

console.log(
  email.padStart(20, "*")
);

These methods make common string checks and formatting tasks much easier to read than older patterns with indexOf() and manual concatenation.

How Modern String Methods Work

String methods are called on a string value and return a new result. They do not modify the original string because JavaScript strings cannot be changed in place.

Step Description Example Syntax
Start with String Use a string value or variable. const text = "hello"
Call Method Invoke the desired string method. text.includes("he")
Get Result Receive boolean, string, or array output. true or "**hello"
Chain Safely Combine methods when useful. text.trim().toLowerCase()
Original Unchanged Source string stays the same. text is still "hello"

Search with includes()

const message =
  "Welcome to modern JavaScript";

console.log(
  message.includes("JavaScript")
);

console.log(
  message.includes("python")
);

console.log(
  message.includes("script", 10)
);

includes() returns true or false depending on whether a substring exists. The optional second argument sets the starting search position.

Check Prefix and Suffix

const fileName =
  "report-2026.pdf";

console.log(
  fileName.startsWith("report")
);

console.log(
  fileName.endsWith(".pdf")
);

console.log(
  fileName.startsWith("2026", 7)
);

startsWith() and endsWith() are ideal for file extensions, protocol checks, route matching, and input validation.

Repeat and Pad Strings

console.log(
  "*".repeat(10)
);

console.log(
  "42".padStart(5, "0")
);

console.log(
  "Hi".padEnd(6, ".")
);

const id = "7";

console.log(
  `ID-${id.padStart(4, "0")}`
);

repeat() duplicates a string, while padStart() and padEnd() add characters until the string reaches a target length.

Trim Whitespace

const input =
  "   hello world   ";

console.log(input.trim());
console.log(input.trimStart());
console.log(input.trimEnd());

const cleaned =
  input.trim().toLowerCase();

console.log(cleaned);

trim(), trimStart(), and trimEnd() remove whitespace from strings. They are commonly used before validating form input.

Replace All Matches

const sentence =
  "cat and cat and cat";

console.log(
  sentence.replace("cat", "dog")
);

console.log(
  sentence.replaceAll("cat", "dog")
);

const tags =
  "html,css,js";

const list =
  tags.replaceAll(",", ", ");

console.log(list);

replace() changes only the first match unless a global regex is used. replaceAll() replaces every occurrence with a simpler syntax.

Access Characters with at()

const word = "JavaScript";

console.log(word[0]);
console.log(word.at(0));
console.log(word.at(-1));
console.log(word.at(-4));

const empty = "";
console.log(empty.at(0));

at() supports negative indexes, making it easier to read characters from the end of a string than bracket notation alone.

Normalize Unicode Text

const composed = "café";
const decomposed = "caf\u0065\u0301";

console.log(composed === decomposed);

console.log(
  composed.normalize("NFC") ===
  decomposed.normalize("NFC")
);

normalize() helps compare strings that look the same but use different Unicode representations. This is useful in search and authentication flows.

Practical Validation Helper

function isValidEmail(value) {
  const email =
    value.trim().toLowerCase();

  return (
    email.includes("@") &&
    email.includes(".") &&
    !email.startsWith("@") &&
    !email.endsWith("@")
  );
}

console.log(
  isValidEmail("  Alex@Example.COM  ")
);

console.log(
  isValidEmail("@invalid.com")
);

Modern string methods combine well in validation helpers because they are readable and expressive for common text checks.

Common Modern String Methods

Method Description Example
includes() Checks whether a substring exists. "abc".includes("b")
startsWith() Checks whether a string starts with text. "file.txt".startsWith("file")
endsWith() Checks whether a string ends with text. "file.txt".endsWith(".txt")
repeat() Repeats a string. "-".repeat(5)
padStart() Pads the start of a string. "7".padStart(3, "0")
padEnd() Pads the end of a string. "Hi".padEnd(5, ".")
trimStart() Removes leading whitespace. " hi".trimStart()
trimEnd() Removes trailing whitespace. "hi ".trimEnd()
replaceAll() Replaces all matches in a string. "a-a".replaceAll("a", "b")
at() Gets a character by index, including negative indexes. "ES6".at(-1)

Common Modern String Method Use Cases

  • Validating emails, usernames, and file names.
  • Filtering search results and tags.
  • Formatting IDs, dates, and counters with padding.
  • Cleaning user input before saving or comparing.
  • Checking URL prefixes and file extensions.
  • Replacing tokens or separators in text templates.

Modern String Method Best Practices

  • Prefer includes() over indexOf() !== -1 for readability.
  • Trim user input before validation and comparison.
  • Use padStart() for numeric formatting such as invoice IDs.
  • Use replaceAll() when every match must change.
  • Normalize text before comparing user-entered values.
  • Remember that string methods return new values and do not mutate the original.
  • Chain methods carefully to keep code readable.

Common String Method Mistakes

  • Expecting string methods to modify the original string.
  • Using replace() when replaceAll() is needed.
  • Forgetting to trim input before validation.
  • Assuming includes() checks word boundaries.
  • Using repeat() with unsafe or very large counts.
  • Comparing Unicode text without normalize().
  • Relying on string[index] for emoji-safe character access instead of considering Unicode behavior.

Modern Methods vs Legacy Patterns

Task Modern Method Legacy Pattern
Contains text text.includes("abc") text.indexOf("abc") !== -1
Starts with text.startsWith("pre") text.indexOf("pre") === 0
Replace all text.replaceAll("a", "b") text.replace(/a/g, "b")
Last character text.at(-1) text[text.length - 1]

Key Takeaways

  • ES6+ added many readable string methods for search, formatting, and cleanup.
  • includes(), startsWith(), and endsWith() simplify common checks.
  • padStart(), padEnd(), and repeat() help with formatting.
  • replaceAll(), at(), and normalize() solve newer text-processing needs.
  • Strings are immutable, so methods always return new results.

Pro Tip

When cleaning user input, start with trim() and toLowerCase(), then apply checks like includes() or startsWith(). This keeps validation helpers short and easy to test.