CodeBlanks Logo Icon CodeBlanks

Summary - Advanced string methods

Build a function that reverses a sentence word by word using split, map and join.

Summary - Advanced string methods

In this group you met the advanced string methods. With slice and substring you took parts; with replace and replaceAll you swapped values; with split and join you moved between strings and arrays.

trim, padStart and padEnd cleaned whitespace and padded to a target width. Finally toUpperCase, toLowerCase and includes handled case work.

Practice Reverse a sentence word by word

Split the sentence string into words, reverse their order with map and join them back with a space. Store the result in reversed and print it. Hint: inside map you can use arr[arr.length - 1 - i].

Starter code

script.js
const sentence = "javascript is a great language";
// split words, reverse their order, join
const reversed = sentence;
console.log(reversed);

Sample solution

script.js
const sentence = "javascript is a great language";
// split words, reverse their order, join
const reversed = sentence.split(" ").map((word, i, arr) => arr[arr.length - 1 - i]).join(" ");
console.log(reversed);

Practice Build a slug from a title

Build a slug from title: first trim the spaces, then lowercase with toLowerCase, then replace every space with a dash. Store the result in slug and print it.

Starter code

script.js
const title = "  JavaScript Lessons  ";
// trim, lowercase, replace spaces with dashes
const slug = title;
console.log(slug);

Sample solution

script.js
const title = "  JavaScript Lessons  ";
// trim, lowercase, replace spaces with dashes
const slug = title.trim().toLowerCase().replaceAll(" ", "-");
console.log(slug);

Questions and answers

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

1 Match method to use

Term Meaning
slice(-3) last three chars
replaceAll("a","b") change all a
split(",") split on comma
trim() strip edge spaces

2 Split the sentence into words and join with a dash

Question
const sentence = "javascript is a great language";
const slug = sentence.____("-").trim();
console.log(slug);
Answer
const sentence = "javascript is a great language";
const slug = sentence.split(" ").join("-").trim();
console.log(slug);

Explanation: split(" ").join("-") glues the words with a dash.

All lessons in Beginner