String Methods

Updated · 7 min read
easyES2026javascriptstringsstring-methodsinterview

String methods are built-in functions that every string has, used to extract, transform and clean text. Because strings are immutable, every method returns a new string (or another value) and leaves the original untouched. Cleaning form input, formatting a receipt, and splitting a line of CSV data all come down to a handful of these methods.

In One Minute

  • Extract: slice(start, end) (supports negative indexes). substring is similar; substr is legacy.
  • Change: toUpperCase, toLowerCase, trim, trimStart, trimEnd, padStart, padEnd, repeat.
  • Replace: replace changes the first match, replaceAll changes every match.
  • Convert: split(separator) turns a string into an array; array.join goes back.
  • Methods can be chained: input.trim().toLowerCase().

Method Table

MethodDescription
slice(start, end)It is used to extract the part from start up to (not including) end. Negative values count from the end.
substring(start, end)It is used to extract a part like slice, but negative values become 0 and swapped arguments are reordered.
toUpperCase() / toLowerCase()It is used to convert every letter to upper or lower case.
trim() / trimStart() / trimEnd()It is used to remove whitespace from both ends, the start, or the end.
padStart(length, fill) / padEnd(...)It is used to add characters at the start or end until the string reaches length.
repeat(count)It is used to repeat the string count times.
split(separator, limit)It is used to split the string into an array of parts.
replace(pattern, replacement)It is used to replace the first match (or every match with a regular expression and the g flag).
replaceAll(pattern, replacement)It is used to replace every match.
concat(...strings)It is used to join strings (template literals are usually clearer).
charAt(i) / at(i)It is used to read one character; at accepts negative indexes.
charCodeAt(i) / codePointAt(i)It is used to read a character's numeric code.
normalize(form)It is used to make visually identical Unicode text compare equal.
localeCompare(other)It is used to compare strings in human alphabetical order (string search lesson).

Extracting Parts: slice and substring

slice.js▶ Try it
const code = "FEE-2026-0042";
 
console.log(code.slice(0, 3));
console.log(code.slice(4, 8));
console.log(code.slice(9));
console.log(code.slice(-4));
console.log(code.substring(4, 8));
Output
FEE
2026
0042
0042
2026

Explanation: slice(0, 3) takes characters at indexes 0, 1 and 2. Leaving out end goes to the end of the string. A negative start counts from the end, so slice(-4) is the last four characters.

slicesubstringsubstr (legacy)
Argumentsstart, endstart, endstart, length
Negative valuesCount from the endTreated as 0Start counts from the end
start > endReturns ""Swaps themn/a
Use it?YesRarelyNo (Annex B, kept only for old code)

Changing Case and Trimming

case-trim.js▶ Try it
const typed = "   navika@EXAMPLE.com  ";
 
console.log(`[${typed.trim()}]`);
console.log(`[${typed.trimStart()}]`);
console.log(typed.trim().toLowerCase());
console.log("dallas".toUpperCase());
Output
[navika@EXAMPLE.com]
[navika@EXAMPLE.com  ]
navika@example.com
DALLAS

trim removes spaces, tabs and line breaks from both ends, never from the middle. Chaining trim().toLowerCase() is the standard way to normalize an email address before comparing or storing it.

For case-insensitive comparison of words in other languages, there are locale-aware versions, toLocaleUpperCase("tr") and friends, because some languages have special case rules.

Padding and Repeating

padStart and padEnd line up columns and add leading zeros:

pad.js▶ Try it
console.log("42".padStart(4, "0"));
console.log("7".padStart(2, "0") + "/" + "5".padStart(2, "0") + "/2026");
 
const rows = [["Tuition", 400], ["Books", 85], ["Lab", 45]];
for (const [item, fee] of rows) {
  console.log(item.padEnd(10, ".") + String(fee).padStart(5));
}
console.log("-".repeat(15));
Output
0042
07/05/2026
Tuition...  400
Books.....   85
Lab.......   45
---------------

If the string is already at least as long as the target, padStart and padEnd return it unchanged; they never cut text.

Splitting and Joining

split breaks a string into an array at every separator. join is its opposite:

split.js▶ Try it
const line = "Navika,Dallas,120";
const [name, city, fee] = line.split(",");
console.log(name, city, Number(fee));
 
console.log("Navika Srihitha  Advitha".split(" "));
console.log("abc".split(""));
console.log("a-b-c-d".split("-", 2));
console.log(["2026", "01", "05"].join("-"));
Output
Navika Dallas 120
['Navika', 'Srihitha', '', 'Advitha']
['a', 'b', 'c']
['a', 'b']
2026-01-05

Explanation: the double space produces an empty string between the two separators. To split on any amount of whitespace, use a regular expression: str.trim().split(/\s+/). split("") splits into UTF-16 code units (which breaks emoji; use [...str] for characters). The second argument limits how many parts are returned.

Replacing Text

replace changes the first match; replaceAll changes every match:

replace.js▶ Try it
const note = "late fee, late notice, late again";
 
console.log(note.replace("late", "LATE"));
console.log(note.replaceAll("late", "LATE"));
console.log("(214) 555-0100".replace(/\D/g, ""));
console.log("navika anamaneni".replace(/\b\w/g, (letter) => letter.toUpperCase()));
Output
LATE fee, late notice, late again
LATE fee, LATE notice, LATE again
2145550100
Navika Anamaneni

Explanation: with a plain string pattern, replace changes only the first occurrence. The last two lines use regular expressions (/\D/g means "every non-digit"; /\b\w/g means "every letter at the start of a word"). A function as the replacement receives each match and returns its replacement. The regular expressions chapter covers both in depth.

In Practice

The Fee Tracker turns messy form input into a clean record: trimmed, normalized name casing, digits-only phone, and a padded receipt number:

clean.js▶ Try it
function cleanRecord(form, sequence) {
  const name = form.name
    .trim()
    .toLowerCase()
    .split(/\s+/)
    .map((word) => word[0].toUpperCase() + word.slice(1))
    .join(" ");
  const phone = form.phone.replace(/\D/g, "");
  const receipt = `R-${String(sequence).padStart(5, "0")}`;
  return { name, phone, receipt };
}
 
console.log(cleanRecord({ name: "  ADVITHA   anamaneni ", phone: "(415) 555-0199" }, 42));
Output
{ name: 'Advitha Anamaneni', phone: '4155550199', receipt: 'R-00042' }

Common Mistakes

Not storing the result. name.trim(); alone changes nothing. Write name = name.trim();.

Expecting replace("a", "b") to replace every match. It replaces the first. Use replaceAll, or a regular expression with the g flag.

Using substr. It takes a length, not an end index, and is a legacy feature. Use slice.

slice with an end smaller than the start. "abc".slice(2, 1) is "", not "b". Check the order.

Interview Corner

What is the difference between slice, substring and substr?

slice(start, end) supports negative indexes and returns "" when start is after end. substring(start, end) clamps negatives to 0 and swaps the arguments if start is greater. substr(start, length) takes a length and is a legacy Annex B method. Prefer slice.

How do you replace all occurrences of a substring?

str.replaceAll("old", "new") (ES2021), or str.replace(/old/g, "new") with a global regular expression. Before ES2021 the idiom was str.split("old").join("new"). With a string pattern, replace changes only the first match.

What does this print?

Show solution
puzzle.js▶ Try it
const s = "  Fee  ";
s.trim();
console.log(`[${s}]`, s.trim().length, "abc".slice(-2), "a,b,,c".split(",").length);
Output
[  Fee  ] 3 bc 4

s.trim() on its own line is thrown away, so s keeps its spaces. The empty field between the two commas still counts as a part, giving four.

Practice

Challenge: Write maskCard(number) that keeps only the last four digits of a card number (which may contain spaces or dashes) and replaces the rest with *, so "4111 1111 1111 1234" becomes "************1234".

Show solution
mask.js▶ Try it
function maskCard(number) {
  const digits = number.replace(/\D/g, "");
  return digits.slice(-4).padStart(digits.length, "*");
}
 
console.log(maskCard("4111 1111 1111 1234"));
console.log(maskCard("5500-0000-0000-0004"));
Output
************1234
************0004

Quick check: String methods

3 questions
1What does "Anamaneni".slice(-3) return?
2Which method replaces every occurrence of a plain string?
3What does "5".padStart(3, "0") return?

Key Takeaways

TaskMethod
Last 4 charactersstr.slice(-4)
Clean inputstr.trim().toLowerCase()
Leading zerosString(n).padStart(5, "0")
Words to arraystr.trim().split(/\s+/)
Replace everywherestr.replaceAll("a", "b")

Was this tutorial helpful?

Lesson 21 of 139