![]() |
VOOZH | about |
The substring() method is used to extract a portion of a string. It returns a new string without changing the original one.
Syntax
string.substring(startIndex, endIndex);Parameters
Return value
One common use case for substring() is when you need to extract specific substrings from a known index range. For example, you might extract the first name or last name from a full name string.
You can use substring() to extract parts of a URL, such as the protocol, domain, or path.
substring() can be used in string validation checks, such as checking whether a specific portion of a string matches a pattern.
If you need to remove a prefix or suffix from a string, you can use substring() to extract the part of the string that remains.
The substring() method does not support negative indices; it converts them to 0, so extraction always starts from the beginning of the string rather than from the end.
If the start index is greater than the end index, substring() automatically swaps them, ensuring the correct substring is extracted without errors.
If only the starting index is provided, substring() will return the substring from that index to the end of the string.
Like most string methods in JavaScript, substring() does not alter the original string. Instead, it returns a new string.