Definition and Usage
The slice() function for strings
slices a string by a specified index range and returns a new string.
Using this function, you can easily slice and extract a string within the desired range.
Features
- The string sliced by the specified index range is returned as a new string.
- The index range is determined by the start and end parameters you specify (the end index is not included).
- With this behavior, the original string remains unchanged.
In strings, indexes start at 0.
'ABC'.slice(0, 2); ๐ 'AB'
Basic Example
/**
* A function that slices a specific range of a string
* and returns the result as a new string.
*
* str.slice(beginIndex[, endIndex])
*
* @param {number} beginIndex - The starting index of the substring to extract.
* @param {number} endIndex - The ending index of the substring to extract (not included).
* @returns {string} - The extracted substring.
*/
/*
* Note:
* In strings, indexes start at 0.
* The first character has an index of 0, and the second character has an index of 1.
*/
const greeting = "Welcome. This is codingCourses.";
const welcome = greeting.slice(0, 7);
console.log(welcome); // Output: "Welcome"
const courseName = greeting.slice(17, 31);
console.log(courseName); // Output: "codingCourses"
/* ๐ The original string remains unchanged. */
console.log(greeting); // Output: "Welcome. This is codingCourses."
In arrays, the array slice() function slices elements within a specified range and returns the result as a new array.
Syntax
str.slice(beginIndex[, endIndex])
str is the string to which the slice() function is applied.
Parameters
beginIndex |
If omitted, the default value is 0.
|
|---|---|
endIndex |
Optional. Specifies the index at which to end extraction.
slice() extracts characters up to, but not including this endIndex index.
|
Return value
The slice() function for strings extracts characters from the original string within the specified index range and returns them as a new string. The returned string is a copy of the selected characters, so the original string remains unchanged.
Parameter and Return Value Examples
let str1 = "Welcome!", // The length of str1 is 8
str2 = str1.slice(1, 8),
str3 = str1.slice(4, -1),
str4 = str1.slice(),
str5 = str1.slice(30);
console.log(str2); // Output: "elcome!"
console.log(str3); // Output: "ome"
console.log(str4); // Output: "Welcome!"
console.log(str5); // Output: ""
Important Notes: Slicing Emojis
In JavaScript, string functions such as slice() and substring() calculate indexes based on UTF-16 code units, not on the number of characters as humans perceive them.
Most common characters within the Basic Multilingual Plane (BMP) are represented by a single code unit. However, more complex characters like emojis are represented using a surrogate pair, which consists of two UTF-16 code units.
// ๐จ An example sliced by code units
"๐๐๐
".slice(0, 2);
// Result: "๐"
// It may appear as if two characters were sliced,
// but only two code units were extracted,
// so only the first emoji is returned.
// โ A dangerous example that slices an emoji in the middle
"๐๐๐
".slice(0, 1);
// Result: a broken character
// Only half of a surrogate pair is extracted,
// which corrupts the character data.
Because slice() processes strings at the UTF-16 code unit level, it is not suitable when your goal is to slice strings containing emojis by human-recognized characters (code points).
To safely process strings containing emojis at the character (code point) level, a different approach is required.
As discussed earlier, since slice() operates on UTF-16 code units, it cannot be used directly when you need to handle emojis as individual characters (code points).
To solve this problem, the string must first be converted so that it is recognized by Unicode characters (code points) rather than code units.
Two modern and recommended approaches are outlined below.
Using the Spread Syntax or Array.from()
The spread syntax (...) and Array.from() convert a string into an array by following JavaScript's string iteration protocol, which treats surrogate pairs as a single Unicode character (code point).
How This Works
- Conversion: '๐๐' โ ['๐', '๐']
- Manipulation: The array
slice()function operates on elements, not code units - Reassembly: The elements are joined back into a string using
join()
const emojiString = "๐๐๐
๐ต";
// Convert the string into a character-level array using the spread syntax
const emojiArray = [...emojiString];
// ["๐", "๐", "๐
", "๐ต"]
// Safely slice the desired number of characters
const result = emojiArray.slice(0, 2).join("");
console.log(result);
// Output: "๐๐"
This approach allows you to safely process strings containing emojis at the character level, exactly as users perceive them.
Differences Between the slice() and substring() Functions
The slice() and substring() functions behave very similarly, but there are a few subtle differences in how they handle their arguments.
Additional Explanation
The substring() function extracts a portion of a string.
It returns a new string containing the characters from the specified start index up to, but not including, the end index.
The table below compares the key differences between the slice() and substring() functions.
| Difference | slice() |
substring() |
|---|---|---|
| Negative index support | Negative values are counted backward from the end of the string. | Negative values are treated as 0. |
| When the start index is greater than the end index | No index swapping occurs. An empty string ("") is returned. |
The two values are automatically swapped and processed. |
const str = "JavaScript";
// slice()
console.log(str.slice(4, 1)); // "" (empty string)
// substring()
console.log(str.substring(4, 1)); // "ava"
Practical Examples
The slice() function is useful in a wide range of situations when working with strings in JavaScript. Below are some common and representative use cases.
Extracting a Substring
The slice() function is commonly used to extract a specific range of characters from a string. This makes it easy to obtain only the portion of the string you need.
const originalString = "Hello, World!";
const slicedString = originalString.slice(0, 5);
console.log(slicedString); // Output: "Hello"
Modifying Part of a String
By extracting a portion of a string and combining it with another string, you can create a new modified string.
const greeting = "Hello";
const modifiedGreeting = greeting.slice(0, 3) + "p!";
console.log(modifiedGreeting); // Output: "Help!"
Removing Part of a String
he slice() function can also be used to remove a specific portion of a string by extracting only the parts you want to keep and concatenating them.
const originalString = "Hello, JavaScript!";
const stringWithoutSegment =
originalString.slice(0, 5) + originalString.slice(-1);
console.log(stringWithoutSegment); // Output: "Hello!"
Specifications
| Specification | |
|---|---|
slice()
|
ECMAScriptยฎ 2026 Language Specification #sec-string.prototype.slice |
Compatibility
| Method |
Desktop Chrome
|
DesktopDesktop Edge
|
Desktop Firefox
|
Safari
|
Node.js
|
|---|---|---|---|---|---|
slice()
|
1 | 12 | 1 | 1 | 0.10 |