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.
Exercise 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].
Show example solution
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);
Exercise 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.
Show example solution
const title = " JavaScript Lessons ";
// trim, lowercase, replace spaces with dashes
const slug = title.trim().toLowerCase().replaceAll(" ", "-");
console.log(slug);
Test yourself
-
Match method to use
- slice(-3)
- last three chars
- replaceAll("a","b")
- change all a
- split(",")
- split on comma
- trim()
- strip edge spaces
-
Split the sentence into words and join with a dash
const sentence = "javascript is a great language"; const slug = sentence.____("-").trim(); console.log(slug);Show answer
const sentence = "javascript is a great language"; const slug = sentence.split(" ").join("-").trim(); console.log(slug);