Hassan khan
Last updated: December 22,2022
Javascript Substring Method
Substring is a built-in method of javascript that extract a specific part of a string. We can pass two parameters to this method. The first parameter is compulsory while the second one is not.
Syntax: substring(startIndex) Or substring(startIndex, endIndex).
If we pass only the first parameter then it will extract the substring from the given index to the end of the actual string.
Example
1 2 3
const myString = 'Hello world!'; // Output: "lo world!" console.log(myString.substring(3));
If we pass all parameters(two) then it will extract only the substring between them but keep in mind the last index will not be included.
Example
1 2 3
const myString = 'Hello world!'; // Output: "world" console.log(myString.substring(6, 11));
- If the start index is greater than the end index then it will swap e.g substring(3, 1) will be equal to substring(1, 3).
- If the start index or end index is less than 0 then it will consider 0.