Slicing and Splitting Strings
Taking a piece out of a string and breaking one into a list are the two operations that turn raw text into usable data.
slice takes a section by position and accepts negative numbers. split breaks a string into an array on a separator, and join puts an array back together. replace swaps one piece of text for another.
EXERCISE
1slice: Taking a Section
slice copies part of a string, from one position up to but not including another.
Two positions, start and end:
const text = "JavaScript";
console.log(text.slice(0, 4)); // Java
console.log(text.slice(4)); // Script no end means "to the finish"
console.log(text.slice(4, 10)); // Script
The end position is not included, which is deliberate:
const text = "abcdef";
console.log(text.slice(1, 3)); // bc positions 1 and 2, not 3
console.log(text.slice(0, 0)); // "" empty
// The useful consequence: end minus start is the length you get.
console.log(text.slice(2, 5).length); // 3
Negative numbers count from the end:
const file = "report.pdf";
console.log(file.slice(-3)); // pdf
console.log(file.slice(-4)); // .pdf
console.log(file.slice(0, -4)); // report
A common pair of jobs:
function truncate(text, max) {
if (text.length <= max) return text;
return text.slice(0, max) + "...";
}
console.log(truncate("A very long headline indeed", 10)); // A very lon...
console.log(truncate("Short", 10)); // Short
function initials(fullName) {
return fullName
.split(" ")
.map((part) => part[0].toUpperCase())
.join("");
}
console.log(initials("ada lovelace")); // AL
split, map and join are coming up in this lesson and the next unit.
"Up to but not including" is the same rule arrays use, and it is worth getting comfortable with now. It means slice(0, 4) gives you exactly four characters, and that slice(a, b) followed by slice(b) reassembles the original with nothing lost or repeated.
EXERCISE
2split and join: Text to List and Back
split breaks a string into an array wherever it finds a separator, and join does the reverse.
split takes a separator and gives you an array:
const csv = "Ada,Grace,Alan";
console.log(csv.split(",")); // [ 'Ada', 'Grace', 'Alan' ]
const sentence = "the quick brown fox";
console.log(sentence.split(" ")); // [ 'the', 'quick', 'brown', 'fox' ]
Two special separators:
// An empty string splits into individual characters:
console.log("cat".split("")); // [ 'c', 'a', 't' ]
// A separator that is not there gives one item:
console.log("no commas here".split(",")); // [ 'no commas here' ]
join puts an array back together:
const parts = ["Ada", "Grace", "Alan"];
console.log(parts.join(", ")); // Ada, Grace, Alan
console.log(parts.join(" and "));// Ada and Grace and Alan
console.log(parts.join("")); // AdaGraceAlan
console.log(parts.join()); // Ada,Grace,Alan comma is the default
Together, they let you transform text:
const date = "2026-09-19";
const [year, month, day] = date.split("-");
console.log(`${day}/${month}/${year}`); // 19/09/2026
// Reversing a string, which has no built-in method:
console.log("hello".split("").reverse().join("")); // olleh
Watch the empty edges:
console.log(",a,b,".split(",")); // [ '', 'a', 'b', '' ]
// A separator at the very start or end produces an empty string.
Pro Tip:
splitandjoinare the bridge between text and lists, and once you can cross it freely, a great deal becomes easy: reversing a string, counting words, reformatting a date, turning a comma-separated field into something you can loop over. Almost every text problem starts by choosing the right separator.
EXERCISE
3replace and replaceAll
Swapping one piece of text for another looks simple and has one behaviour that surprises everybody exactly once.
replace changes the first match only:
const text = "cat cat cat";
console.log(text.replace("cat", "dog")); // dog cat cat
console.log(text); // cat cat cat <- unchanged
That first-match-only behaviour is the surprise. It is not a bug, but it is rarely what people expect.
replaceAll changes every match:
console.log("cat cat cat".replaceAll("cat", "dog")); // dog dog dog
Practical uses:
// Tidy up a phone number
const phone = "+91 98765 43210";
console.log(phone.replaceAll(" ", "")); // +919876543210
// Make a URL-friendly slug
function slugify(title) {
return title.trim().toLowerCase().replaceAll(" ", "-");
}
console.log(slugify(" My First Post ")); // my-first-post
// Swap a placeholder in a template
const template = "Hello NAME, welcome to SITE";
console.log(template.replace("NAME", "Ada").replace("SITE", "DevLoom"));
// Hello Ada, welcome to DevLoom
Chaining, because every method returns a new string:
const messy = " Hello World ";
const clean = messy
.trim()
.toLowerCase()
.replaceAll(" ", " ");
console.log(clean); // hello world
console.log(messy); // " Hello World " <- still untouched
Pro Tip: Reach for
replaceAllby default andreplaceonly when you genuinely mean the first occurrence, because the silent half-finished replacement is a bug that passes a quick eyeball test. And remember that neither one changes the original, so if you are not storing the result, nothing happened.
