- Syntax of String.prototype.slice()
- Parameters Included in String Slice() Method
- Return Values
- Using slice() to create a new string
- Using String slice() with negative indexes
Return a new string from the part of the string included between the
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"
slice(beginIndex) slice(beginIndex, endIndex)
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.
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.
endIndex is defined, then beginIndex should be smaller than endIndex otherwise, an empty string is returned. (For example,
slice(-1, -3), or
slice(3, 1) returns
It returns a part or a slice of the furnished input 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: ""
The following example uses slice() with negative indexes.
<script> var str = "Javatpoint"; document.writeln(str.slice(-5)); </script>