The slice method in JavaScript strings is utilized to extract a portion of the string and produces a new string as a result. To obtain the desired segment of the string, it is necessary to define the index numbers for both the starting and ending parameters. The indexing begins at 0.
This technique enables us to utilize a negative integer as an index. When a negative number is provided, the method begins retrieving characters from the conclusion of the string. Importantly, this process does not alter the original string.
Syntax
The syntax for the slice method is illustrated as follows:
string.slice(start,end)
Parameter
It signifies the index in the string from which the retrieval begins.
end - This parameter is optional. It indicates the position up to which the string is retrieved. In simpler terms, the end parameter is excluded from the fetched portion.
Return
Part of the string
JavaScript String slice Method Example
Let's see some simple examples of slice method.
Example 1
In this section, we will extract a segment of the string by specifying both the starting and ending indices.
<script>
var str = "Example";
document.writeln(str.slice(2,5));
</script>
Output:
Example 2
In this scenario, we will supply only the starting index. In this case, the method retrieves the string up to its total length.
<script>
var str = "Example";
document.writeln(str.slice(0));
</script>
Output:
Example
Example 3
Here is yet another instance in which we supply solely the initial index.
<script>
var str = "Example";
document.writeln(str.slice(4));
</script>
Output:
Example
Example 4
In this instance, we will use a negative value as an index. When this occurs, the method begins retrieving characters from the conclusion of the string.
<script>
var str = "Example";
document.writeln(str.slice(-5));
</script>
Output:
Example 5
In this demonstration, we will utilize negative numbers as both the starting and ending indices. In this scenario, the method will begin retrieving characters from the conclusion of the string.
var str = "Example";
document.writeln(str.slice(-5,-1));
Output: