Skip to content
  • String Methods · JavaScript

String Methods

LearnViaNotes @learnvianotes· 2 min read

Every string method returns a new string (or a value) — the original never changes.

Cheat sheet

MethodPurposeExample → result
includes / startsWith / endsWithSearch → boolean'hello'.startsWith('he') → true
indexOf / lastIndexOfPosition or -1'banana'.indexOf('a') → 1
slice(start, end)Substring; negatives count from end'hello'.slice(-3) → 'llo'
toUpperCase / toLowerCaseCase'Hi'.toUpperCase() → 'HI'
trim / trimStart / trimEndRemove whitespace' x '.trim() → 'x'
padStart / padEndPad to a length'5'.padStart(3, '0') → '005'
repeat(n)Repeat'ab'.repeat(3) → 'ababab'
split(sep)String → array'a,b'.split(',') → ['a', 'b']
replace / replaceAllSubstitute (string or regex)'a-a'.replaceAll('-', '+')
at(i)Index with negatives'abc'.at(-1) → 'c'
localeCompareLocale-aware compare for sorting'a'.localeCompare('b') → -1

In action

JavaScript
const text = "  The quick brown fox  ";
const t = text.trim();
console.log(`[${t}]`, t.length);
console.log(t.includes("quick"), t.indexOf("o"), t.lastIndexOf("o"));
console.log(t.split(" "), t.split(" ", 2));
console.log(t.replace("o", "0"), "|", t.replaceAll("o", "0"));
console.log(t.replace(/o/g, (m) => m.toUpperCase()));
console.log("7".padStart(3, "0"), "ab".padEnd(5, "."), "=".repeat(5));
Output
[The quick brown fox] 19
true 12 17
[ 'The', 'quick', 'brown', 'fox' ] [ 'The', 'quick' ]
The quick br0wn fox | The quick br0wn f0x
The quick brOwn fOx
007 ab... =====

Common interview manipulations

JavaScript
const reverse = (s) => [...s].reverse().join("");
const isPalindrome = (s) => {
  const clean = s.toLowerCase().replace(/[^a-z0-9]/g, "");
  return clean === reverse(clean);
};
const capitalize = (s) => s.charAt(0).toUpperCase() + s.slice(1);
const titleCase = (s) => s.split(" ").map(capitalize).join(" ");
const countChars = (s) =>
  [...s].reduce((acc, ch) => ({ ...acc, [ch]: (acc[ch] ?? 0) + 1 }), {});

console.log(reverse("hello"));
console.log(isPalindrome("A man, a plan, a canal: Panama"));
console.log(titleCase("learn via notes"));
console.log(countChars("banana"));
Output
olleh
true
Learn Via Notes
{ b: 1, a: 3, n: 2 }

substring vs slice vs substr

MethodNegative indicesstart > endStatus
slice(s, e)Count from endReturns ''Use this
substring(s, e)Treated as 0Swaps the argumentsOK
substr(s, len)Start may be negativeSecond arg is a lengthDeprecated

How do you reverse a string in JavaScript?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report