JavaScript Functions and Methods: A Topic-by-Topic Reference · Lesson 4 of 12

Lesson 4: String Methods, Part 2: Split, Replace and Compare

split, join, replace, replaceAll, localeCompare, normalize, template literals, tagged templates and building text.

Lesson 4: String Methods, Part 2: Split, Replace and Compare

Splitting and joining

split(separator, limit)

Break a string into an array. With "" it gives characters.

console.log("a,b,c".split(","));
console.log("Hello".split(""));
console.log("a b  c".split(" "));
console.log("a b  c".split(/\s+/));
console.log("2026-10-04".split("-", 2));

Output:

[ 'a', 'b', 'c' ]
[ 'H', 'e', 'l', 'l', 'o' ]
[ 'a', 'b', '', 'c' ]
[ 'a', 'b', 'c' ]
[ '2026', '10' ]

Array.join(glue)

The opposite of split.

console.log(["red", "green", "blue"].join(", "));
console.log([1, 2, 3].join(""));
console.log("Mero Sir".split(" ").join("-"));

Output:

red, green, blue
123
Mero-Sir

Replacing

replace(find, with) and replaceAll(find, with)

replace changes only the first match when you pass text; replaceAll changes every match.

console.log("a-b-c".replace("-", "+"));
console.log("a-b-c".replaceAll("-", "+"));
console.log("a-b-c".replace(/-/g, "+"));

Output:

a+b-c
a+b+c
a+b+c

replace with a function or $1

Build the replacement from the match. $1, $2 refer to groups.

console.log("john smith".replace(/(\w+) (\w+)/, "$2, $1"));
console.log("a1b2".replace(/\d/g, (d) => d * 2));
console.log("hello world".replace(/\b\w/g, (c) => c.toUpperCase()));

Output:

smith, john
a2b4
Hello World

Comparing

localeCompare(other)

Compare text the way people expect (accents, language, case). Returns a negative, zero or positive number: use it in sort.

console.log("a".localeCompare("b"), "b".localeCompare("a"), "a".localeCompare("a"));
console.log(["é", "e", "z", "a"].sort((x, y) => x.localeCompare(y)));
console.log("a".localeCompare("A", undefined, { sensitivity: "base" }));

Output:

-1 1 0
[ 'a', 'e', 'é', 'z' ]
0

normalize()

Make two visually identical Unicode strings equal.

const a = "\u00e9";
const b = "e\u0301";
console.log(a === b, a.normalize() === b.normalize());

Output:

false true

Case-insensitive comparison

Compare lower-case versions.

const same = (a, b) => a.toLowerCase() === b.toLowerCase();
console.log(same("Nepal", "NEPAL"));

Output:

true

Template literals

`${expression}` and multi-line text

Backticks allow values, expressions and line breaks inside text.

const name = "Sita", marks = 92;
console.log(`${name} scored ${marks} (${marks >= 40 ? "pass" : "fail"})`);
console.log(`line 1
line 2`);

Output:

Sita scored 92 (pass)
line 1
line 2

String.raw

Keeps backslashes as they are, handy for file paths and regular expressions.

console.log(String.raw`C:\new\table`);
console.log("C:\new".length, String.raw`C:\new`.length);

Output:

C:\new\table
5 6

Everyday recipes

Title case

Capitalise each word.

const title = (s) => s.toLowerCase().split(" ").map((w) => w[0].toUpperCase() + w.slice(1)).join(" ");
console.log(title("the QUICK brown fox"));

Output:

The Quick Brown Fox

Slugify

Turn a title into a URL-friendly slug.

const slug = (s) => s.toLowerCase().trim().replace(/[^a-z0-9\s-]/g, "").replace(/\s+/g, "-");
console.log(slug("  Hello, World! Learn JS  "));

Output:

hello-world-learn-js

Truncate with ellipsis

Shorten long text.

const cut = (s, n) => (s.length > n ? s.slice(0, n - 1) + "…" : s);
console.log(cut("A very long article title", 12));

Output:

A very long…

Count words and letters

Using split and a loop.

const text = "the cat and the hat";
console.log(text.split(" ").length);
const counts = {};
for (const w of text.split(" ")) counts[w] = (counts[w] || 0) + 1;
console.log(counts);

Output:

5
{ the: 2, cat: 1, and: 1, hat: 1 }

Intl: dates, lists and numbers for people

The Intl object formats for a language or region.

console.log(new Intl.ListFormat("en", { style: "long", type: "conjunction" }).format(["Ram", "Sita", "Hari"]));
console.log(new Intl.NumberFormat("en-IN").format(12345678));
console.log(new Intl.PluralRules("en").select(1), new Intl.PluralRules("en").select(5));

Output:

Ram, Sita, and Hari
1,23,45,678
one other

Try it yourself

  1. Check whether a string is a palindrome, ignoring spaces and capitals.
  2. Convert "first_name" to "firstName" (camelCase) with replace and a function.
  3. Swap the first and last words of a sentence with split and join.

Next lesson: arrays, part 1.

Finished this lesson?Log in to save your progress and pick up where you left off.
Next lesson →

Comments

Loading comments…

MeroSir Team
A free MeroSir course. Run the examples yourself and try the exercises: you learn programming by doing. Spotted a mistake? Use the Report button above the lesson.
Lesson 4: String Methods, Part 2: Split, Replace and Compare | MeroSir