In JavaScript, you can extract a substring from a string using methods like substring(), slice(), or substr() (though substr() is deprecated). Here’s how you can use each method:
1. Using substring(startIndex, endIndex)
Extracts characters between startIndex (inclusive) and endIndex (exclusive).
javascriptCopy code
const str = “Hello, World!”;
const result = str.substring(0, 5); // Extracts “Hello”
console.log(result);
2. Using slice(startIndex, endIndex)
Works similarly to substring(), but it supports negative indices to count from the end.
javascript
Copy code
const str = “Hello, World!”;
const result = str.slice(0, 5); // Extracts “Hello”
console.log(result);
const negativeResult = str.slice(-6); // Extracts “World!”
console.log(negativeResult);
3. Using substr(startIndex, length)
Extracts a substring starting at startIndex with the specified length. Note that this method is deprecated.
javascript
Copy code
const str = “Hello, World!”;
const result = str.substr(0, 5); // Extracts “Hello”
console.log(result);
Recommendation: Use substring() or slice() as they are widely used and not deprecated.