CodeBlanks Logo Icon CodeBlanks

replace and split

Learn to modify strings with .replace and .split.

Replacing with replace

To replace a substring with another you use .replace(search, replacement). "cold-cold".replace("cold", "warm") changes only the first match and returns "warm-cold".

To replace every match you have two options: a regular expression like /cold/g or the .replaceAll() method. "cold-cold".replaceAll("cold", "warm") returns "warm-warm". replace and replaceAll do not modify the original; they return a new string.

Splitting into an array

To break a string into parts you use .split(separator). The string is split wherever the separator appears and the parts are placed in an array. "apple,pear,banana".split(",") returns ["apple", "pear", "banana"].

If the separator is an empty string each character becomes a separate element: "abc".split("") gives ["a", "b", "c"]. split is especially useful for comma-separated values (CSV); you split each line into pieces and reach the fields.

Practice Split the list into an array

The csv variable holds "Notebook,Pen,Eraser". Declare a variable items and assign the result of csv.split(",") to it. Then print items[0] with console.log. The output on a single line must be Notebook.

Starter code

index.js
const csv = "Notebook,Pen,Eraser";
// Declare items with split; print the first element

Sample solution

index.js
const csv = "Notebook,Pen,Eraser";
const items = csv.split(",");
console.log(items[0]);

Expected output

Notebook

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the result of "a-b".replace("-", "/")?

index.js
"a-b".replace("-", "/")
  • "a-b"
  • "a/b" Correct answer
  • "a/b/c"
  • "/"

Explanation: replace changes the first '-' to '/'; the result is "a/b".

2 Match each method to its job

Term Meaning
.replace(x, y) Changes first match
.replaceAll(x, y) Changes every match
.split(x) Splits into array
.slice(a, b) Takes a part

3 Write the split call

Question
const line = "a,b,c";
const parts = line____(",");
Answer
const line = "a,b,c";
const parts = line.split(",");

Explanation: .split breaks the string by separator into an array.

All lessons in Beginner