JavaScript String Methods Cheat Sheet (Live)

JavaScript strings come with built-in methods for searching (includes, indexOf, startsWith), cutting (slice, substring, split), changing case, trimming, padding and replacing. None of them change the original text: strings are immutable, so each method returns a new value. Type any text below to watch every method run on it as you edit.

The methods people reach for most
TaskMethodExample result
Contains a word?"web site".includes("site")true
First 3 characters"website".slice(0, 3)"web"
Last character"website".at(-1)"e"
Words to an array"a b c".split(" ")["a", "b", "c"]
Replace every match"a-b-c".replaceAll("-", "/")"a/b/c"
Zero pad a number"7".padStart(3, "0")"007"

Updated

Reading a method list tells you names; running the methods on your own text tells you behaviour. The live sheet below applies each method to whatever you type, so edge cases such as negative indexes, empty strings and repeated spaces show up immediately. After that come regex replacements and small validation helpers you can paste into a form.

Live string method sheet

Type text and every method below runs on it as you edit.

String methods by group
CallGroupWhat it does
str.lengthInspectNumber of UTF-16 code units
str.at(0)InspectCharacter at a position; negatives count from the end
str.at(-1)InspectLast character
str.charAt(1)InspectCharacter at a position, empty string if out of range
str.charCodeAt(0)InspectUTF-16 code unit number at a position
str.includes("a")Searchtrue if the text appears anywhere
str.startsWith("The")Searchtrue if the string begins with the text
str.endsWith(".")Searchtrue if the string ends with the text
str.indexOf("o")SearchFirst position of the text, or -1
str.lastIndexOf("o")SearchLast position of the text, or -1
str.search(/[0-9]/)SearchPosition of the first regex match, or -1
str.match(/\w+/g)SearchArray of every match with a global regex
str.slice(0, 5)CutPart between two positions
str.slice(-5)CutThe last five characters
str.substring(2, 6)CutPart between two positions, no negatives
str.split(" ")CutArray of pieces split on a separator
str.toUpperCase()ChangeEvery letter in capitals
str.toLowerCase()ChangeEvery letter in lower case
str.trim()ChangeRemoves whitespace at both ends
str.trimStart()ChangeRemoves whitespace at the start
str.trimEnd()ChangeRemoves whitespace at the end
str.padStart(30, ".")ChangePads the front up to a length
str.padEnd(30, ".")ChangePads the end up to a length
str.repeat(2)ChangeThe string joined to itself n times
str.replace("a", "4")ChangeReplaces the first match only
str.replaceAll("a", "4")ChangeReplaces every match
str.concat("!")ChangeJoins strings; + does the same
str.normalize("NFC")ChangeUnicode normal form, useful before comparing
str.localeCompare("m")CompareNegative, 0 or positive for sort order

Try a regex replace

Edit a pattern, flags and replacement to test it on your own text.

Replace with a regular expression

A regex replacement can match patterns rather than fixed text, reorder parts with capture groups, or compute the replacement with a function.

Special patterns inside the replacement string
PatternInserts
$&The whole match
$1, $2The text of a numbered capture group
$<name>The text of a named capture group
$$A literal dollar sign

Regex replace patterns you will reuse

Each line runs on its own. The function form lets you transform every match, here capitalising the first letter of each word.

"2026-10-14".replace(/(\d{4})-(\d{2})-(\d{2})/, "$3/$2/$1"); // "14/10/2026"

"  too   many    spaces ".trim().replace(/\s+/g, " "); // "too many spaces"

"call 555 0100 now".replace(/\d/g, "#"); // "call ### #### now"

"make each word big".replace(/\b\w/g, (ch) => ch.toUpperCase()); // "Make Each Word Big"

"price: 40".replace(/(?<n>\d+)/, "$$$<n>.00"); // "price: $40.00"

Validation and cleanup helpers

Slug, title case, truncate and a basic email check

Small, dependency-free functions for forms and URLs. The email check only catches obvious mistakes; confirm addresses by sending a message.

export const slugify = (text) =>
  text.normalize("NFKD").replace(/[\u0300-\u036f]/g, "")
    .toLowerCase().trim()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "");

export const titleCase = (text) =>
  text.toLowerCase().replace(/\b\w/g, (ch) => ch.toUpperCase());

export const truncate = (text, max) =>
  text.length <= max ? text : text.slice(0, max - 1).trimEnd() + "\u2026";

export const looksLikeEmail = (text) =>
  /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(text.trim());

slugify("Café & Bar Menu"); // "cafe-bar-menu"

Methods to avoid

Older methods MDN lists as deprecated
MethodUse instead
substr(start, length)slice(start, start + length)
anchor(), bold(), link() and the other HTML wrapper methodsBuild elements with the DOM and set textContent

Indexes, negatives and characters

Positions start at 0. at() and slice() accept negative numbers that count back from the end, while charAt() and bracket access do not, which is why text.at(-1) is the tidy way to grab the final character.

JavaScript stores text as UTF-16. Most letters take one unit, but emoji and some scripts take two, so length, slice and charAt can split such a character in half. Array.from(text) or a for...of loop walks real code points instead.

Search methods that return different things

includes, startsWith and endsWith give a boolean. indexOf and lastIndexOf return a position or -1. search takes a regex and also returns a position. match returns the matches, and matchAll returns an iterator of every match with its groups.

Pick by what the next line needs. If you only branch on yes or no, a boolean method reads more clearly than comparing an index with -1.

Cleaning user input

Trim before you validate, because pasted text often carries spaces or line breaks at the ends. Normalise case before comparing, and collapse runs of whitespace with replace(/\s+/g, " ").

Validation in the browser is a convenience for the visitor. Repeat the same checks on the server, since requests can be sent without your page at all.

How it works

  1. Type or paste text into the input. Every row of the live sheet recalculates as you type.
  2. Filter the rows by name or by group, such as Search or Change, to find a method quickly.
  3. Edit the regex pattern and replacement to test replace with capture groups on your text.
  4. Copy the helper functions further down for trimming, slugs, title case and email checks.

Tips

Frequently asked questions

What is the difference between slice and substring?

Both cut out part of a string from a start index up to an end index. slice treats a negative number as counting back from the end, so slice(-3) returns the last three characters. substring treats negatives as zero and swaps the arguments if the start is larger than the end.

How do I replace all occurrences in a string?

Use replaceAll("old", "new") for plain text, or replace with a global regex such as text.replace(/old/g, "new"). Calling replace with a plain string only changes the first match.

How do I use capture groups in a replacement?

Wrap parts of the pattern in parentheses and refer to them as $1, $2 in the replacement string. Named groups written (?<year>\d{4}) are referenced as $<year>, and $& inserts the whole match.

How do I check whether a string is a valid email address?

A simple pattern catches obvious typos, but no regex fully matches the email rules. The most dependable browser check is an input with type="email", which applies the HTML standard's own pattern, followed by sending a confirmation message.

Do string methods change the original variable?

No. A string value cannot be altered after it is created. Methods like toUpperCase return a new string, so you must assign the result: name = name.toUpperCase().

Related: Regex cheat sheet, Regex tester, JavaScript date formatting, localStorage in JavaScript, JavaScript event listeners.

Start for free or see all free tools. We.Inc is free to start, with no card needed. AI building is on paid plans from $20 a month.

More in Guides

We.Inc is an AI-powered website builder you can resell under your own brand. Launch a branded client dashboard, bill on Stripe Connect, and deliver AI-generated websites in minutes. White-label plans start at $99 a month for 25 client sites, with a 7-day free trial and no per-site fees.

Product

Who It's For

Features

Resources

Company

View Sitemap