Home Tools Blog About

JavaScript String Methods Cheat Sheet

JavaScript strings come with methods for searching, slicing, transforming, and converting text. This cheat sheet groups the methods you use most, and notes that strings are immutable so each one returns a new value.

Search and test

Method What it does
includes(s) True if the substring is present
startsWith(s) / endsWith(s) True if the string starts or ends with the text
indexOf(s) Position of a substring, or -1
lastIndexOf(s) Position of a substring, searching from the end
at(i) Character at an index; supports negatives, e.g. at(-1)
charAt(i) Character at an index
match(re) / matchAll(re) Find matches for a regular expression
search(re) Index of the first regular-expression match

Extract and split

Method What it does
slice(start, end) Copy a section; supports negative indexes
substring(start, end) Copy the text between two indexes
substr(start, len) Copy a length of text from a start (legacy)
split(sep) Split the string into an array on a separator

Transform

Method What it does
toUpperCase() / toLowerCase() Change the case of the string
trim() Remove whitespace from both ends
trimStart() / trimEnd() Remove whitespace from one end
padStart(n, s) / padEnd(n, s) Pad to a length with a fill string
repeat(n) Repeat the string n times
replace(a, b) Replace the first match (or all with a global regex)
replaceAll(a, b) Replace every match
normalize() Normalize the Unicode form of the string

Build and convert

Method What it does
String(x) Convert any value to a string
`Hi ${name}` Template literal: embed values inside backticks
JSON.stringify(x) Convert a value to JSON text
Number(s) / parseInt(s) Convert text to a number
s.length The number of code units in the string

Frequently Asked Questions

Are JavaScript strings mutable?

No. Strings are immutable, so any method that appears to change a string actually returns a new string and leaves the original alone.

What is the difference between slice and substring?

Both copy part of a string. slice accepts negative indexes counting from the end. substring treats negatives as 0 and swaps the two arguments if they are out of order.

How do I replace all occurrences of text?

Use replaceAll(a, b), or replace with a global regular expression such as /x/g. Plain replace changes only the first match.

How do I check whether a string contains text?

Use includes(text), which returns true or false. Use indexOf(text) when you also need the position of the match.

Pair this with our developer and text tools for encoding, formatting, and more.

ATV

Written by Nick (ATV Team)

We build and maintain the 600+ free, client-side tools on this site, and every guide is written against the tools themselves: each figure is computed and checked before it is published, and every linked tool is tested in the browser. More about how we work on the about page, and the full library of guides lives on the blog.