The substring function in JavaScript retrieves a segment of a string based on the specified index and produces a new substring. It functions akin to the slice method, but with the distinction that it does not support negative indices. Notably, the original string remains unaltered when using this method.
Syntax
The syntax for the substring method is as follows:
string.substring(start,end)
Parameter
Begin - It denotes the index of the string indicating the starting point for retrieval.
The "end" parameter is not mandatory. It specifies the endpoint where the string extraction stops.
Return
Part of the string.
JavaScript String substring Method Example
Let's explore a few basic instances showcasing the functionality of the substring function.
Example 1
Here is a basic illustration demonstrating how to output a specific section of a string.
<script>
var str="Example";
document.writeln(str.substring(0,4));
</script>
Output:
Example 2
In this instance, we will retrieve a single character from a given string.
<script>
var str="Example";
document.writeln(str.substring(4,5));
</script>
Output:
Example 3
In this instance, we will solely furnish the initial index.
<script>
var str="Example";
document.writeln(str.substring(5));
</script>
Output:
Example 4
In this instance, we will demonstrate calling the method without passing any parameters. In this scenario, the method will return the entire string.
<script>
var str="Example";
document.writeln(str.substring());
</script>
Output:
Example