SyntaxStudy
Sign Up
JavaScript String Methods: slice, substring, replace, split
JavaScript Beginner 6 min read

String Methods: slice, substring, replace, split

Core String Methods — Part 2

Beyond searching, you frequently need to extract portions of a string, substitute content, or break a string into an array of smaller pieces. JavaScript provides dedicated methods for all of these tasks.

slice(start, end)

slice extracts a section of a string from start up to but not including end. Negative indices count from the end of the string, making it easy to grab a suffix without knowing the full length.

substring(start, end)

substring is similar to slice but treats negative arguments as zero and swaps the arguments if start is greater than end. Prefer slice in modern code for its more predictable behaviour.

replace and replaceAll

replace(pattern, replacement) substitutes the first match of a string or regular expression. replaceAll substitutes every match. The replacement can be a string or a function that receives the matched text and returns the substitution.

split(separator)

split divides a string into an array of substrings. Pass a separator string or regex, and an optional limit on the number of elements returned.

Example
const str = 'Hello, JavaScript World';
console.log(str.slice(7, 17));      // JavaScript
console.log(str.slice(-5));         // World
console.log(str.substring(7, 17));  // JavaScript
console.log(str.replace('Hello', 'Hi')); // Hi, JavaScript World
const csv = 'a,b,c,d';
console.log(csv.split(','));  // ['a','b','c','d']
console.log(csv.split(',', 2)); // ['a','b']
const spaced = '  trim me  ';
console.log(spaced.trim());    // 'trim me'
Pro Tip

When you need to replace every occurrence of a plain string, use replaceAll() rather than a global regex — it is more readable and less error-prone.