Lesson 32 +15 XP

String Methods

String Methods

JavaScript gives strings many built-in methods.

Case conversion

"Hello".toUpperCase(); // "HELLO"
"Hello".toLowerCase(); // "hello"

Trimming spaces

"  hi  ".trim(); // "hi"

Extracting parts

"Hello World".slice(0, 5); // "Hello"
"Hello World".substring(0, 5); // "Hello"

slice and substring grab a section of the string.

Replacing text

"Hello World".replace("World", "JS"); // "Hello JS"

Splitting into arrays

"a,b,c".split(","); // ["a", "b", "c"]

Checking content

"Hello".includes("ell"); // true
"Hello".startsWith("He"); // true
"Hello".endsWith("lo"); // true

The split/join pair

split turns a string into an array. join turns an array back into a string.

TL;DR

  • toUpperCase and toLowerCase change case.
  • trim removes whitespace.
  • slice and substring extract parts.
  • replace swaps text.
  • split turns a string into an array.