The substring() method in JavaScript is similar to slice(), but it has slightly different behavior when dealing with negative indices.
Syntax: string.substring(startIndex, endIndex)
- string: The string from which we want to extract the substring.
- startIndex: The index where the extraction will begin. If negative, it is treated as 0.
- endIndex (optional): The index before which the extraction will end. If omitted, substring() extracts to the end of the string. If negative or greater than the string length, it is treated as the string length.
Example:
let str = "Hello, World!";
let subString = str.substring(7, 12);
console.log(subString); // Output: World
Explanation:
- We have a string str containing the text "Hello, World!".
- We use substring(7, 12) to extract a substring starting from index 7 (inclusive) to index 12 (exclusive).
- The extracted substring is "World", which is then stored in the variable subString and logged to the console.
Online code compiler: https://app.singhteekam.in/codecompiler/