JavaScript String Methods

Beginner
⏱️ 15 min read
📚 Updated: Jul 2026
🎯 51 Tutorials
Text & strings

What You’ll Learn

Strings hold almost every piece of text in JavaScript — names, messages, URLs, and JSON. This hub links to 51 live tutorials today and catalogs 52 String methods for search, slice, trim, replace, padding, and validation.

01

Immutable

Never mutate

02

Search

includes / indexOf

03

Extract

slice / split

04

Transform

trim / case

05

Template

`${value}`

06

52 methods

Full index

Introduction

A JavaScript string is an ordered sequence of characters used for names, messages, file paths, and API payloads. You create them with quotes, template literals, or String() — then call methods to search, slice, and format text without writing character-by-character loops.

What Are String Methods?

String methods live on String.prototype and are available on every string primitive through auto-boxing. Groups include search & test (includes, startsWith, indexOf), extract & split (slice, split), transform (trim, toUpperCase, padStart), and replace (replace, replaceAll). Every method returns a new string — originals never change.

💡
Beginner Tip

Prefer string primitives ("hello") over new String("hello") object wrappers. Primitives are faster, compare predictably with ===, and still expose all prototype methods.

Primitives vs String Objects

  • Primitiveconst name = "Alex"; — the normal, recommended form.
  • Object wrappernew String("Alex") — rare; typeof returns "object".
  • Auto-boxing — JavaScript temporarily wraps primitives when you call name.trim().

Template Literals vs Concatenation

  • Template literals`Hello, ${name}!` — interpolation and multiline text.
  • Plus operator"Hello, " + name + "!" — fine for short joins.
  • concat()"Hello, ".concat(name, "!") — explicit but less common today.

📝 Syntax

Common string patterns — note each call returns a new value:

JavaScript
const text = "  Hello, World!  ";

const clean = text.trim().toLowerCase();
const slug = clean.replace(/\s+/g, "-");
const preview = slug.slice(0, 10);

const greeting = `Welcome, ${name}!`;  // template literal

Method groups

GroupExamplesPurpose
Search & testincludes(), startsWith(), indexOf()Find or validate substrings
Extract & splitslice(), substring(), split()Pull out parts or tokenize
Transformtrim(), toUpperCase(), padStart()Clean, case, and pad text
Replacereplace(), replaceAll()Swap matched text
StaticString.fromCharCode()Build strings from code units

⚡ Quick Reference

GoalMethod
Character count (UTF-16)str.length
Contains substringstr.includes("foo")
Extract a sectionstr.slice(start, end)
Split into arraystr.split(",")
Remove whitespacestr.trim()
Pad to widthstr.padStart(5, "0")
Replace textstr.replace("old", "new")
Dynamic message`Hello, ${name}`

When to Use Which Methods

  • User input cleanuptrim() before validation; combine with toLowerCase() for email-style checks.
  • Prefix / suffix guardsstartsWith() and endsWith() for URLs, file extensions, and command parsing.
  • Tokenizing CSV or pathssplit() then array.join() to rebuild.
  • Display formattingpadStart() for zero-padded IDs; template literals for sentences.
  • Non-destructive edits — chain slice(), replace(), and case methods — assign the final result.
  • Regex-heavy work — pair match(), search(), and replace() with the RegExp hub.

👀 Method Chaining (Immutable)

Each step returns a new string — the original is untouched:

" hello world " .trim() → "hello world" .toUpperCase() → "HELLO WORLD" .replace("WORLD","JS") → "HELLO JS" .slice(0, 5) → "HELLO"

String Properties & Methods Index

Search by name or browse by category. Each tutorial includes syntax, five try-it examples, and FAQs. The catalog covers 52 methods — 49 method tutorials live now plus 3 properties.

String Properties

3 tutorials

Core String object properties every beginner should know first.

PropertyDescriptionTutorial
String constructorCreate string primitives with String() or the rare new String() object wrapper.Open
lengthRead-only character count (UTF-16 code units) of a string.Open
prototypeShared object where String instance methods like slice() and trim() live.Coming soon

HTML Wrapper Methods (Deprecated)

13 tutorials

Legacy helpers that build HTML strings. Prefer document.createElement() in new code.

MethodDescriptionTutorial
anchor()Deprecated HTML wrapper: returns a string with <a name="..."> markup — prefer document.createElement().Open
big()Deprecated HTML wrapper: returns a string with <big> markup — prefer CSS font-size.Open
blink()Deprecated HTML wrapper: returns a string with <blink> markup — avoid blinking text.Open
bold()Deprecated HTML wrapper: returns a string with <b> markup — prefer createElement or CSS font-weight.Open
fixed()Deprecated HTML wrapper: returns a string with <tt> markup — prefer CSS font-family: monospace.Open
fontcolor()Deprecated HTML wrapper: returns a string with <font color="..."> markup — prefer CSS color.Open
fontsize()Deprecated HTML wrapper: returns a string with <font size="..."> markup — prefer CSS font-size.Open
italics()Deprecated HTML wrapper: returns a string with <i> markup — prefer createElement or CSS font-style.Open
link()Deprecated HTML wrapper: returns a string with <a href="..."> markup — prefer document.createElement("a").Open
small()Deprecated HTML wrapper: returns a string with <small> markup — prefer createElement("small") or CSS font-size.Open
strike()Deprecated HTML wrapper: returns a string with <strike> markup — prefer createElement("s") or createElement("del").Open
sub()Deprecated HTML wrapper: returns a string with <sub> markup — prefer document.createElement("sub").Open
sup()Deprecated HTML wrapper: returns a string with <sup> markup — prefer document.createElement("sup").Open

Character Access

5 tutorials

Read characters, code units, code points, or iterate the string.

MethodDescriptionTutorial
at()Return the UTF-16 code unit at an index — supports negative offsets from the end (at(-1) is last).Open
charAt()Return the UTF-16 code unit at a zero-based index — out of range returns "" (no negative indexes).Open
charCodeAt()Return the UTF-16 code unit at an index as a number (0–65535) — out of range returns NaN.Open
codePointAt()Return the full Unicode code point at a UTF-16 index — out of range returns undefined (handles emoji).Open
[Symbol.iterator]()Make strings iterable by Unicode code points — powers for...of and spread; surrogate pairs stay together.Open

Unicode & Well-Formed

3 tutorials

Normalize Unicode forms and detect or repair lone UTF-16 surrogates.

MethodDescriptionTutorial
isWellFormed()Return true if the string has no lone UTF-16 surrogates — useful before encodeURI(); pair with toWellFormed().Open
toWellFormed()Replace lone UTF-16 surrogates with U+FFFD (�) — safe for encodeURI(); pair with isWellFormed().Open
normalize()Return a Unicode Normalization Form (NFC/NFD/NFKC/NFKD) — default NFC; use before comparing lookalike text.Open

Extract & Split

4 tutorials

Pull out parts of a string or split into arrays.

MethodDescriptionTutorial
slice()Extract a section into a new string — exclusive end index; negatives count from the end.Open
substring()Extract between two indexes (exclusive end) — swaps if start > end; negatives treated as 0.Open
substr()Legacy start+length extractor (deprecated Annex B) — prefer slice(); negative length returns "".Open
split()Divide a string into an array by a string or regex separator — optional limit; capturing groups appear in the result.Open

Transform & Pad

10 tutorials

Change case, trim whitespace, pad, or repeat text.

MethodDescriptionTutorial
toLowerCase()Convert to lowercase with Unicode default mappings — great for case-insensitive compares; no locales arg.Open
toUpperCase()Converts all characters to uppercase.Coming soon
toLocaleLowerCase()Locale-aware lowercase — optional BCP 47 locales; Turkish İ differs from toLowerCase().Open
toLocaleUpperCase()Locale-aware uppercase — optional BCP 47 locales; Turkish i → İ; length may grow (ß → SS).Open
trim()Remove whitespace from both ends — spaces, tabs, newlines; middle spaces kept; pair with trimStart/trimEnd.Open
trimStart()Remove leading whitespace only — keeps trailing spaces; alias trimLeft(); pair with trim/trimEnd.Open
trimEnd()Remove trailing whitespace only — keeps leading spaces; alias trimRight(); pair with trim/trimStart.Open
padStart()Pad the start of a string to a target length — default space filler; great for zero-padding and masks.Open
padEnd()Pad the end of a string to a target length — default space filler; padString repeats or truncates.Open
repeat()Build a new string by concatenating the original count times — RangeError for negative or Infinity.Open

Combine & Replace

3 tutorials

Join strings or swap matched text for new content.

MethodDescriptionTutorial
concat()Joins two or more strings into a new string without mutating originals.Coming soon
replace()Replace the first string match or regex matches — use g for all; support $ groups and replacer functions.Open
replaceAll()Replace every string or global-regex match — TypeError if a RegExp is missing the g flag.Open

Compare & Convert

3 tutorials

Sort-friendly comparison and primitive conversion.

MethodDescriptionTutorial
localeCompare()Locale-aware string ordering — returns <0 / 0 / >0; optional locales and options (sensitivity, numeric).Open
toString()Return the string primitive — unwraps new String(...); same as valueOf(); TypeError for non-string this.Open
valueOf()Return the string primitive — same as toString(); unwraps new String(...); usually called by the engine.Open

Static Methods

3 tutorials

Helpers on the String constructor — not called on an instance.

MethodDescriptionTutorial
fromCharCode()Static helper: build a string from UTF-16 code units (0–65535) — pair with charCodeAt(); prefer fromCodePoint() for emoji.Open
fromCodePoint()Static helper: build a string from full Unicode code points (0–0x10FFFF) — emoji in one arg; invalid values throw RangeError.Open
raw()Static template tag: keep escape sequences raw while still evaluating ${} — great for paths and RegExp sources.Open

Examples Gallery

Open DevTools Console (F12) and paste each snippet. Remember: every method returns a new string.

📚 Transform & Chain

Immutable pipelines that build new strings step by step.

Example 1 — Chain toUpperCase(), replace(), and slice()

Normalize text, swap a word, then take a short preview — without mutating the source.

JavaScript
const raw = "  hello world  ";

const result = raw
  .trim()
  .toUpperCase()
  .replace("WORLD", "JavaScript")
  .slice(0, 11);

console.log(result);       // "HELLO JAVAS"
console.log(raw);          // still "  hello world  "
slice() in index

How It Works

Each method returns a new string, so you can chain calls left to right. The original raw variable keeps its whitespace because strings are immutable.

🔎 Search & Validate

Test whether text contains or begins with expected values.

Example 2 — Validate with includes() and startsWith()

Guard routes and file uploads with readable boolean checks.

JavaScript
function isSafePath(path) {
  if (path.includes("..")) return false;
  if (!path.startsWith("/app/")) return false;
  return true;
}

console.log(isSafePath("/app/home"));     // true
console.log(isSafePath("/app/../etc"));   // false

How It Works

includes() scans anywhere in the string; startsWith() checks the prefix. Both return booleans — ideal for early returns in validation helpers.

Example 3 — Split and Join

Turn comma-separated values into an array, modify, then rebuild a string.

JavaScript
const csv = "apple,banana,cherry";

const items = csv.split(",");
items.push("date");

const updated = items.join(" | ");
console.log(updated);  // "apple | banana | cherry | date"
split() in index

How It Works

split() breaks a string into an array; Array.prototype.join() stitches it back. Pair this pattern with the Array hub when you need map or filter in between.

🛠 Clean & Format

Whitespace cleanup and fixed-width display.

Example 4 — Trim User Input

Remove accidental spaces before comparing or saving form data.

JavaScript
const username = "  codetofun  ";

const cleaned = username.trim();
console.log(cleaned.length);           // 9
console.log(cleaned === "codetofun");  // true
trim() in index

How It Works

trim() strips leading and trailing whitespace (spaces, tabs, newlines). Use trimStart() or trimEnd() when you only need one side removed.

Example 5 — Zero-Pad IDs with padStart()

Align numeric strings to a fixed width for filenames or invoice numbers.

JavaScript
const orderId = 42;

const formatted = String(orderId).padStart(5, "0");
console.log(formatted);           // "00042"
console.log(`INV-${formatted}`);  // "INV-00042"

How It Works

padStart(targetLength, fillString) repeats the fill character on the left until the string reaches the desired length. Combine with template literals for readable labels.

💬 Usage Tips

  • Assign resultstext = text.trim(); calling trim() alone does nothing unless you store the return value.
  • Prefer slice over substrsubstr() is legacy; slice() supports negative indexes from the end.
  • Case-insensitive checks — normalize with toLowerCase() before includes() when comparing user input.
  • Emoji-aware lengthlength counts UTF-16 code units; use [...str].length or codePointAt() when grapheme count matters.
  • Search this index — jump to any of 51 live tutorials or scan the 52-method catalog above.

⚠️ Common Pitfalls

  • Expecting mutationstr.toUpperCase() without assignment leaves str unchanged.
  • String object confusionnew String("a") === new String("a") is false (different objects).
  • Emoji length"😀".length === 2 surprises beginners; plan for surrogate pairs in UI limits.
  • replace vs replaceAllreplace() swaps only the first match unless you pass a global regex.
  • Sort as strings"10" < "2" lexically; parse numbers before comparing when needed.

🧠 How String Methods Work

1

Primitive value

Text lives as an immutable UTF-16 sequence — literals, templates, or String().

Create
2

Auto-box & call

JavaScript temporarily wraps the primitive to reach String.prototype methods.

Invoke
3

New string returned

Search, slice, trim, and replace produce fresh strings — chain or assign the result.

Transform
=

Reliable text handling

Validate input, format output, and integrate with arrays and regex — without manual character loops.

Browser Support

Core String methods like slice, trim, split, and includes are supported in every modern browser and Node.js. Newer helpers such as replaceAll, padStart, and at are widely available in current engines.

Baseline · ES3+ / ES2015+

String.prototype methods

Supported in Chrome, Firefox, Safari, Edge, and all maintained Node.js releases. Locale methods depend on the host Intl implementation; UTF-16 length behavior is consistent everywhere.

100% Core API
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
String methods Universal

Bottom line: Production-safe across modern environments. Use feature checks only for very new APIs like replaceAll in legacy browsers, or polyfill when supporting IE11.

🎉 Conclusion

JavaScript strings are immutable text values with a rich toolkit for search, extraction, transformation, and formatting. Start with properties like length, then chain trim(), slice(), and template literals in real code.

Use the searchable index for 51 live tutorials today and the full 52-method catalog as new pages ship — each includes try-it labs and FAQs.

💡 Best Practices

✅ Do

  • Use template literals for dynamic messages
  • Assign results from trim, replace, slice
  • Normalize case before loose comparisons
  • Prefer includes/startsWith over indexOf === 0
  • Plan for UTF-16 length with emoji in UI

❌ Don’t

  • Wrap strings in new String() objects
  • Assume methods mutate the original
  • Use substr() in new code
  • Compare numbers stored as strings with <
  • Memorize all 52 names at once

Key Takeaways

Knowledge Unlocked

Five things to remember about String methods

Your gateway to 52 methods and 51 live tutorials.

5
Core concepts
2 02

UTF-16

length caveat

Emoji
` 03

Templates

${interp}

Modern
🔗 04

Chain

trim → slice

Pattern
52 05

Index

Search all

Ref

❓ Frequently Asked Questions

String methods are functions on String.prototype (or the String constructor for static helpers) that search, extract, transform, and format text. Examples include slice(), trim(), split(), replace(), includes(), and padStart(). They always return new values — strings never mutate in place.
No. Strings are immutable. Methods like toUpperCase() and replace() return a new string; the original stays the same. To update a variable, assign the result: text = text.trim().
A primitive like "hello" is the normal, lightweight form. new String("hello") wraps text in an object — rarely needed and can confuse typeof checks. Prefer primitives and let JavaScript auto-box them when you call methods.
JavaScript strings use UTF-16 code units. Many emoji and rare characters occupy two code units (a surrogate pair). Use codePointAt(), [...str], or Intl.Segmenter when you need true grapheme counts.
Template literals (backticks) are the modern default — they support interpolation (${name}) and multiline text. Use + or concat() for simple joins when you prefer, but backticks are clearer for dynamic messages.
Read the overview, try the five examples, then open the String constructor from Properties. Use the search box to browse 51 live tutorials and the full catalog of 52 String methods.
Did you know?

When you write "hello"[0], JavaScript coerces the primitive to a String object, reads index 0, then discards the wrapper. Bracket access is convenient, but charAt() and at() make intent clearer in tutorials.

Start with the String constructor

Learn how primitives are created and why object wrappers are rare.

String constructor tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

10 people found this page helpful