Tutorial JavaScript Developer Tools Cheat Sheet

Free JavaScript String Methods Cheat Sheet Online — Interactive Reference for Developers

· 12 min read

Strings are the most frequently manipulated data type in JavaScript. Every web application — from a simple contact form to a real-time collaborative editor — depends on string operations for user input handling, URL parsing, data validation, HTML generation, API response processing, and countless other tasks. The JavaScript String prototype defines over forty built-in methods, and developers constantly reach for them during daily coding, code reviews, and technical interviews. Yet the exact syntax, parameter order, and behavior edge cases are easy to forget. Does slice support negative indices? What is the difference between substring and substr? How do you replace all occurrences without a regex? Our free interactive JavaScript string methods cheat sheet eliminates this friction. It organizes every method into searchable categories, provides concise syntax references, live code examples, and clear labels for mutating versus non-mutating behavior. Everything runs entirely in your browser — no data ever leaves your machine.

Why Developers Need a JavaScript String Methods Cheat Sheet

String manipulation is deceptively simple. The basic syntax — quotes, concatenation, length — takes minutes to learn. But mastering the full API surface takes years of practice. The ECMAScript specification defines over forty string methods, and new ones arrive with every annual release. Some methods return new strings. Others return indices, booleans, or arrays. Some accept regular expressions. Others accept literal strings or callback functions. Some are case-sensitive. Others are locale-aware. The differences between search and indexOf, match and matchAll, or slice and substring are subtle but significant.

The real problem is retrieval friction. When you are deep in a coding session, switching contexts to search documentation breaks flow. Opening a new tab, typing a query like "js string replace all occurrences", skimming MDN, and finding the right example can consume several minutes. A well-organized javascript string methods cheat sheet reduces that time to seconds. An interactive cheat sheet goes further — it lets you search by method name, filter by category, and copy code examples instantly. Whether you are preparing for a frontend interview, reviewing a pull request, or building a new feature, having every string method at your fingertips keeps you productive.

JavaScript String Basics: A Quick Review

Before diving into methods, let us establish what strings are and why they behave the way they do. In JavaScript, strings are primitive values — immutable sequences of UTF-16 code units. When you call a method on a string, JavaScript temporarily wraps it in a String object, executes the method, and returns a new primitive value. The original string never changes.


const greeting = "hello";
const upper = greeting.toUpperCase();
console.log(upper);    // "HELLO"
console.log(greeting); // "hello" — unchanged

This immutability is fundamental. Every string method returns a new string rather than modifying the original. If you need to "change" a string, you must reassign the variable or create a new one.

Template Literals and Escape Sequences

Modern JavaScript provides three ways to create strings: single quotes, double quotes, and backtick template literals. Template literals support interpolation and multiline strings:


const name = "Alice";
const age = 30;
const message = `Hello, ${name}! You are ${age} years old.`;
console.log(message);
// "Hello, Alice! You are 30 years old."

const multiline = `
  Line 1
  Line 2
  Line 3
`;

Escape sequences allow special characters within strings:


const quote = "She said "hello"";
const newline = "Line 1\nLine 2";
const tab = "Column 1\tColumn 2";
const backslash = "C:\\Users\\Alice";

String Length and Indexing

Strings are zero-indexed. The length property returns the number of UTF-16 code units, which may differ from the number of visible characters for emojis and surrogate pairs:


const str = "hello";
console.log(str.length);  // 5
console.log(str[0]);      // "h"
console.log(str[4]);      // "o"
console.log(str[99]);     // undefined

// Surrogate pairs (emojis) count as 2 code units
const emoji = "🚀";
console.log(emoji.length); // 2

Understanding these fundamentals helps explain why certain methods behave the way they do. Now let us explore the methods themselves.

Search and Find Methods

Searching within strings is one of the most common operations. JavaScript provides multiple methods for finding content, each with different capabilities and return types.

indexOf and lastIndexOf

indexOf returns the first index of a substring, or -1 if not found. It accepts an optional fromIndex parameter to start searching from a specific position:


const str = "The quick brown fox jumps over the lazy dog";
console.log(str.indexOf("fox"));      // 16
console.log(str.indexOf("cat"));      // -1
console.log(str.indexOf("the"));      // 31 (case-sensitive!)
console.log(str.indexOf("the", 32));  // -1

lastIndexOf searches from the end of the string:


const str = "hello world, hello universe";
console.log(str.lastIndexOf("hello")); // 13
console.log(str.lastIndexOf("hello", 12)); // 0

Both methods are case-sensitive and work with literal strings only. For pattern-based searching, use search or regular expressions.

search: Pattern-Based Searching

search accepts a regular expression and returns the index of the first match, or -1 if no match:


const str = "The price is $42.50";
console.log(str.search(/\$\d+\.\d+/)); // 13
console.log(str.search(/\d{3}/));       // -1

Unlike indexOf, search does not support a starting position parameter. Use indexOf for simple literal searches; use search when you need pattern matching.

match and matchAll: Extracting Matches

match returns an array of matches when used with the global flag, or a detailed match object without it:


const str = "Contact us at support@example.com or sales@example.com";

// Without global flag — returns first match with capture groups
const firstMatch = str.match(/([\w.]+)@([\w.]+)/);
console.log(firstMatch[0]); // "support@example.com"
console.log(firstMatch[1]); // "support"
console.log(firstMatch[2]); // "example.com"

// With global flag — returns all matches as strings
const allMatches = str.match(/[\w.]+@[\w.]+/g);
console.log(allMatches); // ["support@example.com", "sales@example.com"]

matchAll (ES2020) returns an iterator of all matches, including capture groups, even with the global flag:


const str = "Contact us at support@example.com or sales@example.com";
const matches = [...str.matchAll(/([\w.]+)@([\w.]+)/g)];

for (const match of matches) {
  console.log(`Full: ${match[0]}, User: ${match[1]}, Domain: ${match[2]}`);
}
// Full: support@example.com, User: support, Domain: example.com
// Full: sales@example.com, User: sales, Domain: example.com

matchAll is the modern replacement for match with global regex when you need capture group information.

charAt, charCodeAt, codePointAt, and at

charAt returns the character at a specific index:


const str = "hello";
console.log(str.charAt(0)); // "h"
console.log(str.charAt(99)); // "" (empty string, not undefined)

charCodeAt returns the UTF-16 code unit at an index:


console.log("A".charCodeAt(0)); // 65
console.log("a".charCodeAt(0)); // 97

codePointAt returns the full Unicode code point, correctly handling surrogate pairs:


const emoji = "🚀";
console.log(emoji.charCodeAt(0));  // 55357 (high surrogate)
console.log(emoji.codePointAt(0)); // 128640 (full code point)

at (ES2022) supports negative indices for accessing characters from the end:


const str = "hello";
console.log(str.at(0));  // "h"
console.log(str.at(-1)); // "o" — last character
console.log(str.at(-2)); // "l" — second to last

at(-1) is much more readable than str[str.length - 1] for accessing the last character.

Replace and Transform Methods

Transforming string content is essential for data cleaning, templating, formatting, and sanitization.

replace: Single Replacement with Regex Power

replace replaces the first occurrence of a pattern. With a string pattern, it replaces only the first match. With a regex and the global flag, it replaces all matches:


const str = "The quick brown fox jumps over the lazy dog";

// Replace first occurrence only
console.log(str.replace("the", "a"));
// "The quick brown fox jumps over a lazy dog"

// Replace all occurrences with regex global flag
console.log(str.replace(/the/gi, "a"));
// "a quick brown fox jumps over a lazy dog"

replace shines when used with capture groups and replacement patterns:


// Reformat date from MM/DD/YYYY to YYYY-MM-DD
const date = "12/25/2023";
const isoDate = date.replace(
  /(\d{2})\/(\d{2})\/(\d{4})/,
  "$3-$1-$2"
);
console.log(isoDate); // "2023-12-25"

// Swap first and last names
const name = "Doe, John";
const fullName = name.replace(/(w+), (w+)/, "$2 $1");
console.log(fullName); // "John Doe"

You can also use a replacement function for dynamic transformations:


// Convert camelCase to snake_case
const camel = "userProfileSettings";
const snake = camel.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`);
console.log(snake); // "user_profile_settings"

// Mask credit card number
const card = "1234-5678-9012-3456";
const masked = card.replace(/\d{4}-\d{4}-\d{4}-(\d{4})/, "****-****-****-$1");
console.log(masked); // "****-****-****-3456"

replaceAll: Global Replacement Made Simple

replaceAll (ES2021) replaces all occurrences of a string without needing regex:


const str = "The quick brown fox jumps over the lazy dog";
console.log(str.replaceAll("the", "a"));
// "The quick brown fox jumps over a lazy dog"

// Note: case-sensitive by default
console.log(str.replaceAll("The", "A"));
// "A quick brown fox jumps over the lazy dog"

Before ES2021, developers used workarounds like split().join() or regex with global flag. replaceAll makes the intent explicit and avoids regex escaping issues.

normalize: Unicode Normalization

normalize converts strings to a standard Unicode form, essential when comparing strings that may contain composed or decomposed characters:


const composed = "caf\u00E9";   // "café" with composed é
const decomposed = "cafe\u0301"; // "café" with e + combining acute

console.log(composed === decomposed);           // false
console.log(composed.normalize() === decomposed.normalize()); // true

// NFC (Canonical Composition) is the default
console.log(composed.normalize("NFC").length);  // 4
console.log(composed.normalize("NFD").length);  // 5

Always normalize user input before comparison or storage when dealing with international text.

repeat: String Multiplication

repeat creates a new string by repeating the original:


console.log("*".repeat(5));      // "*****"
console.log("-".repeat(20));     // "--------------------"
console.log("na ".repeat(4) + "Batman!"); // "na na na na Batman!"

This is cleaner and faster than manual concatenation in a loop.

Split and Join Methods

Breaking strings apart and putting them back together is fundamental for parsing and formatting.

split: Breaking Strings into Arrays

split divides a string into an array of substrings based on a delimiter:


const sentence = "The quick brown fox";
const words = sentence.split(" ");
console.log(words); // ["The", "quick", "brown", "fox"]

const csv = "apple,banana,cherry,date";
const fruits = csv.split(",");
console.log(fruits); // ["apple", "banana", "cherry", "date"]

// Split into characters
const chars = "hello".split("");
console.log(chars); // ["h", "e", "l", "l", "o"]

// Limit the number of results
const limited = "a,b,c,d,e".split(",", 3);
console.log(limited); // ["a", "b", "c"]

split also works with regular expressions for complex delimiters:


// Split on multiple whitespace characters
const messy = "hello   world\tfoo\nbar";
const tokens = messy.split(/\s+/);
console.log(tokens); // ["hello", "world", "foo", "bar"]

concat: String Concatenation

concat joins two or more strings. In modern JavaScript, template literals or the + operator are preferred:


const first = "Hello";
const second = "World";
console.log(first.concat(" ", second, "!")); // "Hello World!"

// Modern alternatives (preferred)
console.log(`${first} ${second}!`); // "Hello World!"
console.log(first + " " + second + "!"); // "Hello World!"

slice, substring, and substr: Extracting Substrings

These three methods extract portions of strings, but they have important differences:


const str = "hello world";

// slice(start, end) — supports negative indices
console.log(str.slice(0, 5));    // "hello"
console.log(str.slice(6));       // "world"
console.log(str.slice(-5));      // "world" (negative = from end)
console.log(str.slice(2, -2));   // "llo wor"

// substring(start, end) — no negative support, swaps if start > end
console.log(str.substring(0, 5));  // "hello"
console.log(str.substring(6));     // "world"
console.log(str.substring(-5));    // "hello world" (negative = 0)
console.log(str.substring(5, 0));  // "hello" (swapped to 0, 5)

// substr(start, length) — DEPRECATED, do not use
console.log(str.substr(6, 5));   // "world"

Prefer slice for all new code. It supports negative indices, does not swap arguments, and is not deprecated. substring is legacy, and substr is officially deprecated.

Case Conversion Methods

Case conversion is essential for normalization, comparison, and display formatting.

toUpperCase and toLowerCase

toUpperCase and toLowerCase convert strings to uppercase and lowercase:


const str = "Hello World";
console.log(str.toUpperCase()); // "HELLO WORLD"
console.log(str.toLowerCase()); // "hello world"

// Common use: case-insensitive comparison
const input = "YES";
if (input.toLowerCase() === "yes") {
  console.log("Confirmed!");
}

toLocaleUpperCase and toLocaleLowerCase

toLocaleUpperCase and toLocaleLowerCase respect locale-specific rules. This matters for languages with special case mappings:


// Turkish "I" problem
const turkish = "istanbul";
console.log(turkish.toUpperCase());           // "ISTANBUL"
console.log(turkish.toLocaleUpperCase("tr")); // "İSTANBUL"

const german = "straße";
console.log(german.toUpperCase());            // "STRASSE"
console.log(german.toLocaleUpperCase("de"));  // "STRASSE"

For user-facing applications with international users, always use locale-aware methods when the locale is known.

URL Slug Generation

A common pattern is generating URL-friendly slugs from titles:


function slugify(title) {
  return title
    .toLowerCase()
    .trim()
    .replace(/[^\w\s-]/g, "")
    .replace(/[\s_-]+/g, "-")
    .replace(/^-+|-+$/g, "");
}

console.log(slugify("Hello World! How are you?"));
// "hello-world-how-are-you"

Trim and Pad Methods

Whitespace handling is critical for form validation, data cleaning, and formatted output.

trim, trimStart, and trimEnd

trim removes whitespace from both ends of a string. trimStart and trimEnd remove whitespace from one side:


const input = "  hello world  ";
console.log(input.trim());      // "hello world"
console.log(input.trimStart()); // "hello world  "
console.log(input.trimEnd());   // "  hello world"

// Essential for form validation
const username = "  alice  ";
const clean = username.trim();
console.log(clean); // "alice"

Always trim user input before validation to prevent accidental whitespace from causing validation failures.

padStart and padEnd

padStart and padEnd pad strings to a target length:


// Zero-pad numbers
const num = "42";
console.log(num.padStart(5, "0")); // "00042"

// Format IDs
const id = "123";
console.log(id.padStart(8, "0")); // "00000123"

// Align text
const items = ["apple", "banana", "cherry"];
items.forEach(item => {
  console.log(item.padEnd(10, ".") + " $2.99");
});
// apple..... $2.99
// banana.... $2.99
// cherry.... $2.99

// Credit card formatting
const card = "1234";
console.log(card.padStart(16, "*")); // "************1234"

Validation and Extraction Methods

Testing string content without extracting it is a common requirement for validation and conditional logic.

includes: Substring Existence Check

includes returns true if a substring exists, false otherwise:


const str = "The quick brown fox";
console.log(str.includes("fox"));     // true
console.log(str.includes("cat"));     // false
console.log(str.includes("Fox"));     // false (case-sensitive)
console.log(str.includes("quick", 4)); // true (start from index 4)

includes is cleaner than indexOf !== -1 for existence checks:


// OLD way
if (str.indexOf("needle") !== -1) { }

// MODERN way
if (str.includes("needle")) { }

startsWith and endsWith

startsWith and endsWith test the beginning and end of strings:


const url = "https://example.com/api/users";
console.log(url.startsWith("https")); // true
console.log(url.endsWith("/users"));   // true

// Check file extension
const file = "document.pdf";
console.log(file.endsWith(".pdf")); // true

// Check protocol
console.log(url.startsWith("http://"));  // false
console.log(url.startsWith("https://")); // true

Both methods accept an optional position parameter:


const str = "hello world";
console.log(str.startsWith("world", 6)); // true
console.log(str.endsWith("hello", 5));   // true

localeCompare: Locale-Aware Comparison

localeCompare compares two strings according to locale-specific rules, returning -1, 0, or 1:


const strings = ["banana", "apple", "cherry", "Apple"];
strings.sort((a, b) => a.localeCompare(b));
console.log(strings); // ["apple", "Apple", "banana", "cherry"]

// Case-insensitive sort
strings.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: "base" }));
console.log(strings); // ["apple", "Apple", "banana", "cherry"]

// German sort (ä sorts with a)
const german = ["äpfel", "apfel", "zebra"];
german.sort((a, b) => a.localeCompare(b, "de"));

Performance: indexOf vs includes vs regex

For simple substring searches, includes and indexOf have similar performance. Use includes for boolean checks (more readable). Use indexOf when you need the position. Avoid regex for simple literal searches — regex compilation adds overhead:


// Fast: simple literal search
if (str.includes("needle")) { }

// Slower: unnecessary regex compilation
if (/needle/.test(str)) { }

// Use regex only when you need pattern matching
if (/\$\d+\.\d{2}/.test(str)) { }

Static Methods

String also provides static methods that are called on the constructor rather than instances.

String.fromCharCode and String.fromCodePoint

fromCharCode creates a string from UTF-16 code units. fromCodePoint (ES2015) handles full Unicode code points including those outside the Basic Multilingual Plane:


console.log(String.fromCharCode(65, 66, 67));     // "ABC"
console.log(String.fromCodePoint(128640));         // "🚀"
console.log(String.fromCodePoint(0x1F600));        // "😀"

// fromCharCode fails for emoji code points
console.log(String.fromCharCode(0x1F600));         // "�" (wrong!)

Always use fromCodePoint when working with emoji or other characters above U+FFFF.

String.raw: Raw Template Strings

String.raw creates a string where escape sequences are not processed:


const path = String.raw`C:\\Users\\Alice\\Documents`;
console.log(path); // "C:\\Users\\Alice\\Documents"

// Compare with regular template literal
const path2 = `C:\\Users\\Alice\\Documents`;
console.log(path2); // "C:\\Users\\Alice\\Documents" (escape sequences processed)

This is useful when working with regular expressions, file paths, or any string where backslashes should be preserved literally.

Comparison Table: slice vs substring vs substr

These three methods cause constant confusion. Here is the definitive comparison:

Featureslice(start, end)substring(start, end)substr(start, length)
Negative indicesYes (counts from end)No (treated as 0)Yes (counts from end)
Swaps arguments if start > endNo (returns empty string)YesN/A (uses length)
Second parameter meaningEnd index (exclusive)End index (exclusive)Length of substring
StatusStandard, recommendedLegacy, avoidDeprecated, avoid
ES specificationActiveActive but legacyDeprecated in Annex B

Recommendation: Use slice exclusively. It has the most predictable behavior, supports negative indices, and is the modern standard.

Common Patterns and Best Practices

After covering individual methods, let us examine practical patterns that combine multiple methods for real-world tasks.

Safe String Concatenation

Template literals are the safest and most readable way to combine strings:


// BAD: implicit coercion surprises
const result = "The answer is " + 42 + 1; // "The answer is 421"

// GOOD: template literals with explicit expressions
const answer = 42;
const result = `The answer is ${answer}`; // "The answer is 42"

// GOOD: multiple values
const name = "Alice";
const age = 30;
const greeting = `Hello, ${name}! You are ${age} years old.`;

Checking for Empty Strings

Empty strings are falsy in JavaScript, but explicit checks are clearer:


function isEmpty(str) {
  return !str || str.trim().length === 0;
}

console.log(isEmpty(""));       // true
console.log(isEmpty("   "));    // true
console.log(isEmpty("hello"));  // false
console.log(isEmpty(null));     // true
console.log(isEmpty(undefined)); // true

Removing Whitespace from User Input

Always clean user input before validation or storage:


function cleanInput(input) {
  return input?.trim().replace(/\s+/g, " ") ?? "";
}

console.log(cleanInput("  hello   world  ")); // "hello world"
console.log(cleanInput(null));               // ""

Parsing Query Strings

Extract URL parameters using split and iteration:


function parseQueryString(query) {
  const params = new Map();
  if (!query || query === "?") return params;

  const clean = query.startsWith("?") ? query.slice(1) : query;

  clean.split("&").forEach(pair => {
    const [key, value = ""] = pair.split("=");
    params.set(decodeURIComponent(key), decodeURIComponent(value));
  });

  return params;
}

const query = "?name=Alice&age=30&city=New%20York";
const params = parseQueryString(query);
console.log(params.get("name")); // "Alice"
console.log(params.get("city")); // "New York"

Multiline Strings

Template literals handle multiline strings cleanly:


const html = `
  <div class="container">
    <h1>${title}</h1>
    <p>${description}</p>
  </div>
`;

// For indentation cleanup
function dedent(str) {
  const lines = str.split("\n");
  const minIndent = lines
    .filter(line => line.trim())
    .reduce((min, line) => {
      const indent = line.match(/^(\s*)/)[1].length;
      return Math.min(min, indent);
    }, Infinity);

  return lines
    .map(line => line.slice(minIndent))
    .join("\n")
    .trim();
}

Performance Considerations

Understanding string performance characteristics helps write efficient code.

String Immutability and Concatenation

Because strings are immutable, repeated concatenation in loops creates many intermediate string objects:


// BAD: O(n²) due to repeated string creation
let result = "";
for (let i = 0; i < 10000; i++) {
  result += String(i);
}

// GOOD: use array join
const parts = [];
for (let i = 0; i < 10000; i++) {
  parts.push(String(i));
}
const result = parts.join("");

For modern JavaScript, this optimization is less critical than it once was — engines have optimized string concatenation significantly. But for very large datasets, array join is still safer.

Regex Compilation Costs

Creating regular expressions inside loops causes repeated compilation:


// BAD: regex recompiled on every iteration
for (const str of strings) {
  if (/\$\d+\.\d{2}/.test(str)) {
    // ...
  }
}

// GOOD: compile once
const pricePattern = /\$\d+\.\d{2}/;
for (const str of strings) {
  if (pricePattern.test(str)) {
    // ...
  }
}

localeCompare for Sorting

When sorting large arrays of strings, localeCompare is slower than simple comparison but necessary for correct results:


// Fast but wrong for international text
strings.sort((a, b) => a > b ? 1 : -1);

// Slower but correct
strings.sort((a, b) => a.localeCompare(b));

// For maximum performance with locale awareness
strings.sort((a, b) => a.localeCompare(b, undefined, { numeric: true }));

Try Our Interactive JavaScript String Methods Cheat Sheet

Reading about string methods is valuable, but having an interactive reference at your fingertips is transformative. Our free JavaScript String Methods Cheat Sheet puts every method into a searchable, filterable interface with these features:

  • Real-time search — find methods by name, description, or example
  • Category filtering — narrow to search, replace, split, trim, case conversion, validation, or static methods
  • Syntax highlighting — code examples are color-coded for readability
  • One-click copy — copy any code example to your clipboard instantly
  • 100% client-side — no data leaves your browser

Bookmark it, share it with your team, and never search for string method syntax again.

Related Developer Tools

DevToolkit offers a growing collection of free developer utilities. Check out these related tools:

Frequently Asked Questions

Are JavaScript strings mutable or immutable?

JavaScript strings are immutable. All string methods return a new string rather than modifying the original. For example, calling toUpperCase() creates and returns a new uppercase string; the original remains unchanged.

What is the difference between slice, substring, and substr in JavaScript?

slice(start, end) supports negative indices and extracts up to but not including the end index. substring(start, end) does not support negatives and swaps arguments if start > end. substr(start, length) is deprecated and returns a substring of given length from start. Prefer slice() for modern code.

How do I replace all occurrences in a JavaScript string?

Use replaceAll(searchValue, replaceValue) for a simple global replacement (ES2021). For regex, use replace(/pattern/g, replacement) with the global flag. Before ES2021, split().join() was a common workaround.

What is the difference between indexOf and search in JavaScript?

indexOf(searchValue, fromIndex) searches for a literal string and returns the first index or -1. It supports a starting position. search(regexp) accepts a regular expression and returns the first match index or -1. Use indexOf for simple literal searches; use search or match for pattern-based searches.

Is the JavaScript String Methods Cheat Sheet free to use?

Yes. The DevToolkit JavaScript String Methods Cheat Sheet is completely free with no limits, no registration, and no advertisements. It runs entirely in your browser with no data sent to any server.

Conclusion

JavaScript string methods are the foundation of text manipulation in modern web development. With over forty methods spanning search, replacement, transformation, extraction, validation, and case conversion, the API is rich but can be overwhelming. Our free interactive JavaScript string methods cheat sheet removes the friction from learning and referencing these methods. Whether you are debugging a regex pattern, preparing for an interview question about slice versus substring, or exploring the new ES2021 replaceAll method, the cheat sheet puts every method, syntax, and example at your fingertips. Bookmark it, share it with your team, and keep shipping better JavaScript.

For related reading, check out our JavaScript Array Methods Cheat Sheet article and try the interactive array methods tool for a complete reference to JavaScript array operations. For the latest language features, see our JavaScript ES2024+ Features Cheat Sheet article and try the interactive ES2024+ tool.

Found this useful? Check out our free developer tools or browse more articles.