JavaScript Tutorial · JavaScript Basics · Lesson 9 of 44

JavaScript String Methods

Search, slice, replace, split, trim and pad strings.

Changing case and trimming

Example 1Try it yourself
const s = "  Hello World  ";
console.log(s.trim());
console.log(s.toUpperCase());
console.log(s.trim().toLowerCase());
console.log("7".padStart(3, "0"));
console.log("ha".repeat(3));

Output

Hello World
  HELLO WORLD  
hello world
007
hahaha

Searching

includes(), startsWith() and endsWith() return booleans; indexOf() returns the position or -1:

Example 2Try it yourself
const email = "[email protected]";
console.log(email.includes("@"));
console.log(email.endsWith(".com"));
console.log(email.startsWith("admin"));
console.log(email.indexOf("@"));
console.log(email.indexOf("#"));

Output

true
true
false
3
-1

Extracting and replacing

slice(start, end) extracts part of a string (negative numbers count from the end). replaceAll() replaces every match; replace() only the first:

Example 3Try it yourself
const text = "I like cats. cats are great.";
console.log(text.slice(2, 6));
console.log(text.slice(-6));
console.log(text.replace("cats", "dogs"));
console.log(text.replaceAll("cats", "dogs"));

Output

like
great.
I like dogs. cats are great.
I like dogs. dogs are great.

Splitting and joining

split() turns a string into an array; an array's join() turns it back:

Example 4Try it yourself
const csv = "red,green,blue";
const colors = csv.split(",");
console.log(colors);
console.log(colors.join(" | "));
console.log("hello".split("").reverse().join(""));

Output

[ 'red', 'green', 'blue' ]
red | green | blue
olleh

Test yourself

What does "JavaScript".slice(0, 4) return?

  1. "Java"
  2. "JavaS"
  3. "avaS"
  4. "Script"
Show answer

Answer: "Java"