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.
| Task | Method | Example 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.
| Call | Group | What it does |
|---|---|---|
| str.length | Inspect | Number of UTF-16 code units |
| str.at(0) | Inspect | Character at a position; negatives count from the end |
| str.at(-1) | Inspect | Last character |
| str.charAt(1) | Inspect | Character at a position, empty string if out of range |
| str.charCodeAt(0) | Inspect | UTF-16 code unit number at a position |
| str.includes("a") | Search | true if the text appears anywhere |
| str.startsWith("The") | Search | true if the string begins with the text |
| str.endsWith(".") | Search | true if the string ends with the text |
| str.indexOf("o") | Search | First position of the text, or -1 |
| str.lastIndexOf("o") | Search | Last position of the text, or -1 |
| str.search(/[0-9]/) | Search | Position of the first regex match, or -1 |
| str.match(/\w+/g) | Search | Array of every match with a global regex |
| str.slice(0, 5) | Cut | Part between two positions |
| str.slice(-5) | Cut | The last five characters |
| str.substring(2, 6) | Cut | Part between two positions, no negatives |
| str.split(" ") | Cut | Array of pieces split on a separator |
| str.toUpperCase() | Change | Every letter in capitals |
| str.toLowerCase() | Change | Every letter in lower case |
| str.trim() | Change | Removes whitespace at both ends |
| str.trimStart() | Change | Removes whitespace at the start |
| str.trimEnd() | Change | Removes whitespace at the end |
| str.padStart(30, ".") | Change | Pads the front up to a length |
| str.padEnd(30, ".") | Change | Pads the end up to a length |
| str.repeat(2) | Change | The string joined to itself n times |
| str.replace("a", "4") | Change | Replaces the first match only |
| str.replaceAll("a", "4") | Change | Replaces every match |
| str.concat("!") | Change | Joins strings; + does the same |
| str.normalize("NFC") | Change | Unicode normal form, useful before comparing |
| str.localeCompare("m") | Compare | Negative, 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.
| Pattern | Inserts |
|---|---|
| $& | The whole match |
| $1, $2 | The 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
| Method | Use instead |
|---|---|
| substr(start, length) | slice(start, start + length) |
| anchor(), bold(), link() and the other HTML wrapper methods | Build 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
- Type or paste text into the input. Every row of the live sheet recalculates as you type.
- Filter the rows by name or by group, such as Search or Change, to find a method quickly.
- Edit the regex pattern and replacement to test replace with capture groups on your text.
- Copy the helper functions further down for trimming, slugs, title case and email checks.
Tips
- Prefer slice over substr. MDN marks substr as deprecated, and slice accepts negative positions from the end.
- replaceAll with a regex needs the g flag, otherwise it throws a TypeError.
- Use localeCompare when sorting names so accents and case sort the way readers expect.
- length counts UTF-16 code units, so a single emoji can report a length of 2. Spread the string into an array to count code points.
- Chaining is fine because each call returns a fresh string: text.trim().toLowerCase().replaceAll(" ", "-").
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.
Build your site free or see all free tools. On We.Inc you can build your site free, with no card and no trial needed to start. AI building is on paid plans from $19 a month.
More in Guides
- JavaScript Websites and AI Crawlers: Can They See Your Pages? | How-to Guide
- Build a Jewelry Website: Pages, Costs and a Working Example | How-to Guide
- Jira MCP Server: Setup, Tools and Admin Controls
- Keyboard and Screen Reader Testing, Step by Step
- Keyword Cannibalization: Find Pages Fighting Over One Search
- How to Link CSS to HTML
- Link to a Sentence: Text Fragment URLs
- Local Citations: Get Your Name, Address and Phone Right Everywhere
Product
Who It's For
- For Agencies
- For Freelancers
- For Hosting Providers
- For SaaS Platforms
- For Startups
- For Financial Services
- For Healthcare
Features
Resources
- Blog
- Help Center
- Free Business Tools
- Free UI Components
- Website Templates
- Template Collections
- Website Examples
- Guides
- Comparisons
- Alternatives
- Best Lists
- Reviews
- Pricing Guides
- Use Cases
- Glossary & Guides
- Integrations
- Developers
- Benchmark
- Windows App