JavaScript Functions and Methods: A Topic-by-Topic Reference · Lesson 3 of 12

Lesson 3: String Methods, Part 1: Searching and Slicing

length, at, charAt, indexOf, includes, startsWith, slice, substring, toUpperCase, trim, padStart, repeat and more.

Lesson 3: String Methods, Part 1: Searching and Slicing

Strings are unchangeable: every method returns a new string. Positions start at 0.

Looking inside

length, charAt(i), at(i), [i]

The size of the string and the character at a position. at accepts negative positions.

const s = "Himalaya";
console.log(s.length);
console.log(s[0], s.charAt(1), s.at(-1));
console.log(s[99], s.charAt(99) === "");

Output:

8
H i a
undefined true

indexOf(x), lastIndexOf(x)

Position of the first or last match, or -1.

const s = "banana";
console.log(s.indexOf("an"), s.lastIndexOf("an"), s.indexOf("z"));
console.log(s.indexOf("a", 2));

Output:

1 3 -1
3

includes(x), startsWith(x), endsWith(x)

True/false checks.

const file = "report.pdf";
console.log(file.includes("port"));
console.log(file.startsWith("rep"), file.endsWith(".pdf"));
console.log("Hello".startsWith("ell", 1));

Output:

true
true true
true

search(regex) and match(regex)

Search with a regular expression (see Lesson 12). search gives a position, match gives the matches.

console.log("order 66".search(/\d/));
console.log("a1b22c333".match(/\d+/g));

Output:

6
[ '1', '22', '333' ]

Cutting

slice(start, end)

A piece from start up to (not including) end. Negative numbers count from the end.

const s = "Programming";
console.log(s.slice(0, 3));
console.log(s.slice(3));
console.log(s.slice(-4));
console.log(s.slice(2, -2));

Output:

Pro
gramming
ming
ogrammi

substring(start, end) and substr

Like slice but it swaps its arguments if they are reversed and treats negatives as 0. Prefer slice.

const s = "Programming";
console.log(s.substring(3, 0));
console.log(s.slice(3, 0) === "");

Output:

Pro
true

Changing case and spacing

toUpperCase(), toLowerCase()

All capitals or all small letters.

console.log("Nepal".toUpperCase(), "NEPAL".toLowerCase());

Output:

NEPAL nepal

trim(), trimStart(), trimEnd()

Remove whitespace from the ends.

console.log("[" + "  hi  ".trim() + "]");
console.log("[" + "  hi  ".trimStart() + "]");
console.log("[" + "  hi  ".trimEnd() + "]");

Output:

[hi]
[hi  ]
[  hi]

padStart(n, fill), padEnd(n, fill)

Pad to a width. Great for numbers and tables.

console.log("7".padStart(3, "0"));
console.log("Rs".padEnd(6, ".") + "|");
console.log(String(5).padStart(2, "0") + ":" + String(9).padStart(2, "0"));

Output:

007
Rs....|
05:09

repeat(n)

Repeat a string.

console.log("ab".repeat(3));
console.log("=".repeat(20));

Output:

ababab
====================

concat() and the + operator

Join strings. Template strings are usually clearer.

const a = "Mero", b = "Sir";
console.log(a.concat(b), a + b, `${a}${b}!`);

Output:

MeroSir MeroSir MeroSir!

Characters and codes

charCodeAt(i), String.fromCharCode(n), codePointAt

The number of a character and back. codePointAt handles all of Unicode.

console.log("A".charCodeAt(0), "a".charCodeAt(0));
console.log(String.fromCharCode(72, 105));
console.log(String.fromCharCode("a".charCodeAt(0) + 2));
console.log("न".codePointAt(0));

Output:

65 97
Hi
c
2344

Iterating over characters

A for...of loop and the spread operator handle each character (including emoji) correctly.

console.log([..."Nepal"]);
console.log("😀a".length, [..."😀a"].length);
for (const ch of "abc") console.log(ch);

Output:

[ 'N', 'e', 'p', 'a', 'l' ]
3 2
a
b
c

Reversing a string

Strings have no reverse: turn into an array, reverse, and join.

const reverse = (s) => [...s].reverse().join("");
console.log(reverse("Kathmandu"));

Output:

udnamhtaK

Try it yourself

  1. Capitalise the first letter of a word using charAt, toUpperCase and slice.
  2. Count how many times a letter appears using a loop and indexOf, or split.
  3. Format 5 as "005" and 12 as "012" with padStart.

Next lesson: String methods, part 2.

Finished this lesson?Log in to save your progress and pick up where you left off.
Next lesson →

Comments

Loading comments…

MeroSir Team
A free MeroSir course. Run the examples yourself and try the exercises: you learn programming by doing. Spotted a mistake? Use the Report button above the lesson.
Lesson 3: String Methods, Part 1: Searching and Slicing | MeroSir