JavaScript(JS) string method - substring

h‮/:sptt‬/www.theitroad.com

The substring() method is a string method in JavaScript that is used to extract a substring from a string.

Here is the syntax for the substring() method:

str.substring(indexStart, indexEnd)

Here, str is the string you want to extract a substring from, indexStart is the starting index of the substring, and indexEnd is the ending index of the substring (exclusive). If indexEnd is not specified, the substring() method will extract the substring to the end of the str.

The substring() method returns the extracted substring as a new string.

Here is an example of using the substring() method:

let str = "hello world";
let result = str.substring(6, 11);
console.log(result); // "world"

In the example above, the substring() method extracts the substring starting at index 6 and ending at index 11 (exclusive) from the str. The resulting substring is "world".

If indexStart is greater than indexEnd, the substring() method will swap the two arguments.

Here is an example of using the substring() method with indexStart greater than indexEnd:

let str = "hello world";
let result = str.substring(11, 6);
console.log(result); // "world"

In the example above, the substring() method swaps the arguments 11 and 6, so the method extracts the substring starting at index 6 and ending at index 11 (exclusive) from the str. The resulting substring is still "world".