Home › Learn › JavaScript › Strings and numbers

String methods

Lesson 26 of 40. Split, join, trim, replace, and search text.

Strings are immutable, so every method returns a new string. The everyday ones: .split(sep) breaks into an array, array.join(sep) glues back, .trim() removes surrounding whitespace, .replace(a, b) swaps the first match and .replaceAll(a, b) every match, .includes, .startsWith, .endsWith, .indexOf, .slice(start, end), .padStart(n, "0"), and .repeat(n).

Chaining reads well: title.trim().toLowerCase().replaceAll(" ", "-"). Each step returns a string and the next runs on that.

const line = "  name: Ada  ";
const [key, value] = line.trim().split(": ");
console.log(key, value);                     // name Ada
console.log("7".padStart(3, "0"));           // 007

Your task

Write slugify(title) turning a title into a URL slug: lower case, trimmed, spaces replaced with hyphens, and every character that is not a letter, digit, or hyphen removed. " Hello World! " becomes "hello-world". Then initials(fullName) returning the first letter of each word in upper case, so "ada byron lovelace" gives "ABL".

Hint 1

title.trim().toLowerCase().replaceAll(" ", "-").replace(/[^a-z0-9-]/g, "")

Hint 2

fullName.split(" ").map((w) => w[0].toUpperCase()).join("")

Show the solution
function slugify(title) {
  return title.trim().toLowerCase().replaceAll(" ", "-").replace(/[^a-z0-9-]/g, "");
}

function initials(fullName) {
  return fullName.split(" ").map((w) => w[0].toUpperCase()).join("");
}

    Runs in an isolated web worker in this tab; nothing is sent anywhere.