How to Extract a Substring in JavaScript
substr, substring, slice, and more
There are three methods for extracting part of a string in JavaScript, maybe too many. One would have been enough
substr
The substr(start, length)
method extracts part of a string, beginning at the specified index and returning the specified number of characters.
const quote = "Winter is coming";const part1 = quote.substr(0, 6);
//Winterconst part2 = quote.substr(10, 6);
//coming
Notice that the first character is at index 0
.
The start
index is required but the length
is optional. If omitted it extracts the rest of the string.
const quote = "Winter is coming";const part = quote.substr(6);
// is coming
substring
The substring(start, end)
method returns the part of a string between the start
and end
indexes. It begins with the character at the start
index and ends but does not include the character at the end
index.
const quote = "We Stand Together";const part = quote.substring(3, 8);
// Stand