The String slice() method in JavaScript | Definition, Syntax, How it works, Examples of JavaScript String slice() method

In this ultimate tutorial, we have discussed complete details about the JavaScript String slice() method like definition, syntax, how to use the string slice() method to extract a substring from a string with examples.

JavaScript String slice() method – Definition

Return a new string from the part of the string included between the begin and end positions.

The original string is not mutated.

end is optional.

"This is my work".slice(5)
//"is my work"
"This is my work".slice(5,10)
//"is my"

If you set a negative first parameter, the start index starts from the end, and the second parameter must be negative as well, always counting from the end:

"This is my work".slice(-4)
//"work"
"This is my work".slice(-4,-1)
//"wor"

String.prototype.slice() Syntax

slice(beginIndex)
slice(beginIndex, endIndex)

Parameters Included in String Slice() Method

1. beginIndex: 

The zero-based index whereat to start extraction. In the case of negative, it is treated as str.length + beginIndex. (For instance, if beginIndexis -2, it is interpreted as str.length – 2.) If beginIndex is not a numeral after Number (beginIndex), it is considered as 0. In case beginIndexis greater than or equal to the str.length, an empty string is returned.

2. endIndex (Optional):

The zero-based index before which to end extraction. The character at this index wouldn’t be involved.

If endIndex is excluded or undefined, or greater than str.length, slice() extracts to the edge of the string. If negative, it is handled as str.length + endIndex. (For instance, if endIndex is -5, it is treated as str.length – 5.) If it is not undefined, and the Number(endIndex) is not positive, an empty string is returned.

If endIndex is defined, then beginIndex should be smaller than endIndex otherwise, an empty string is returned. (For example, slice(-3, 0), slice(-1, -3), or slice(3, 1) returns "".)

Return Values

It returns a part or a slice of the furnished input string.

Do Check:

Examples on String slice() method in JavaScript

In this section, you will find plenty of example programs to learn how to create and use the javascript string slice() method in various conditions:

1. Using slice() to create a new string

The following examples utilize the string slice() method to create a new string.

let str1 = 'The morning is upon us.', // the length of str1 is 23.
    str2 = str1.slice(1, 8),
    str3 = str1.slice(4, -2),
    str4 = str1.slice(12),
    str5 = str1.slice(30);
console.log(str2)  // OUTPUT: he morn
console.log(str3)  // OUTPUT: morning is upon u
console.log(str4)  // OUTPUT: is upon us.
console.log(str5)  // OUTPUT: ""

2. Using slice() with negative indexes

The following example uses slice() with negative indexes.

<script> 
var str = "Javatpoint"; 
document.writeln(str.slice(-5)); 
</script>

Output:

point