Episode 26 of 46

Slice and Split Strings

Learn how to extract parts of strings with slice, substring, and split.

JavaScript provides several methods to extract and divide strings.

slice()

Extracts a portion of a string by start and end position:

let str = "Hello, World!";

str.slice(0, 5);     // "Hello"
str.slice(7);        // "World!" (from position 7 to end)
str.slice(-6);       // "orld!" (from 6th-to-last)
str.slice(0, -1);    // "Hello, World" (remove last char)

substring()

Similar to slice but doesn't accept negative indices:

let str = "Hello, World!";

str.substring(0, 5);   // "Hello"
str.substring(7);      // "World!"
str.substring(7, 12);  // "World"

split()

Splits a string into an array based on a delimiter:

let csv = "apple,banana,cherry,date";
let fruits = csv.split(",");
console.log(fruits);  // ["apple", "banana", "cherry", "date"]

let sentence = "Hello World JavaScript";
let words = sentence.split(" ");
console.log(words);   // ["Hello", "World", "JavaScript"]

// Split every character
let chars = "Hello".split("");
console.log(chars);   // ["H", "e", "l", "l", "o"]

Combining split() and join()

// Replace spaces with dashes
let title = "Hello World JavaScript";
let slug = title.toLowerCase().split(" ").join("-");
console.log(slug);  // "hello-world-javascript"

// Reverse a string
let reversed = "Hello".split("").reverse().join("");
console.log(reversed);  // "olleH"

repeat()

let star = "⭐";
console.log(star.repeat(5));  // "⭐⭐⭐⭐⭐"

let line = "-".repeat(30);
console.log(line);  // "------------------------------"