String .slice() / substring()
Extracts a portion of a string and returns it as a new string. The original string is not modified.
Syntax
// Extracts from the start position to the end of the string. string.slice(startIndex) string.slice(startIndex, endIndex) // Extracts a substring within the specified range. string.substring(startIndex) string.substring(startIndex, endIndex)
Method List
| Method | Description |
|---|---|
| slice(startIndex) | Extracts from the start index to the end of the string. A negative value is treated as an offset from the end. |
| slice(startIndex, endIndex) | Extracts from the start index up to, but not including, the end index. |
| substring(startIndex) | Extracts from the start index to the end of the string. A negative value is treated as 0. |
| substring(startIndex, endIndex) | Extracts from the start index up to, but not including, the end index. If the start index is greater than the end index, the arguments are swapped automatically. |
Sample Code
var str = "JavaScript"; // Extract using slice. console.log(str.slice(4)); // Outputs "Script". console.log(str.slice(0, 4)); // Outputs "Java". console.log(str.slice(-6)); // Extracts 6 characters from the end, outputs "Script". console.log(str.slice(-6, -3)); // Outputs "Scr". // Extract using substring. console.log(str.substring(4)); // Outputs "Script". console.log(str.substring(0, 4)); // Outputs "Java". // Difference between slice and substring. console.log(str.slice(4, 0)); // Returns an empty string "". console.log(str.substring(4, 0)); // Arguments are swapped, outputs "Java".
Overview
string.slice() and string.substring() are both methods for extracting a portion of a string. Both return characters from the start index up to, but not including, the end index, and neither modifies the original string.
The key difference between the two methods lies in how they handle negative values and argument order. string.slice() treats negative values as offsets from the end of the string, making it well-suited for extracting characters from the end. string.substring(), on the other hand, converts negative values to 0 and automatically swaps the arguments if the start index is greater than the end index.
In general, string.slice() behaves more intuitively and is recommended in most situations. Arrays also have a method of the same name, array.slice(), which works in nearly the same way.
Browser Compatibility
3 or earlier ×
3 or earlier ×
Android Browser
37+ ○
4 or earlier ×
Chrome Android
36+ ○
17 or earlier ×
Firefox Android
79+ ○
3 or earlier ×If you find any errors or copyright issues, please contact us.