String. prototype. substring()
Returns a portion of a string between two indexes. Negative values are treated as 0, and reversed indexes are swapped.
- Returns
- A new string with a piece of the original.
- Changes the original
- No
Example
#const lesson = 'Lesson 7: Loops'
console.log(lesson.substring(0, 6))
console.log(lesson.substring(10))Definition and usage
#The substring() method returns the part of a string from indexStart to indexEnd, excluding the character at indexEnd. With positive arguments given in the right order, it works exactly like slice().
The differences show up with unusual arguments. Negative values and NaN are treated as 0, so substring(-3) returns the whole string, not the last three characters. When indexStart is greater than indexEnd, the method silently swaps them.
Those implicit corrections make hard-to-spot bugs easier to introduce, which is why new code usually reaches for slice() instead. Still, it's worth knowing substring(), since it often turns up in older code. Don't confuse it with the deprecated substr() method, whose second argument is a length, not an end index.
Syntax
#string.substring(indexStart)
string.substring(indexStart, indexEnd)Parameters
#indexStart
number
The index of the first character of the result. Negative values andNaNare converted to0.indexEnd
number, optional
The index before which the result ends. Defaults to the string's length. If it is smaller thanindexStart, the arguments are swapped.
More examples
#const text = 'Programming'
console.log(text.substring(-4))
console.log(text.slice(-4))
console.log(text.substring(7, 3))
console.log(text.slice(7, 3).length)const message = 'Congratulations [Emma], module complete!'
const start = message.indexOf('[') + 1
const end = message.indexOf(']')
console.log(message.substring(start, end))Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- In new code, reach for
slice(). It supports negative indexes and does not silently swap arguments, so bugs are easier to spot. - Avoid the deprecated
substr(start, length)method. Its second argument is a length, not an end index, which is easy to mix up.
Related entries
#- String.prototype.slice()Returns a portion of a string from a start index to an end index (not included). Supports negative indexes.
- String.prototype.indexOf()Returns the index of the first occurrence of the given text in a string, or -1 when it is not there.
- String.prototype.split()Splits a string into an array of pieces based on a separator: a character, a string, or a regular expression.
- String.prototype.at()Returns the character at the given index. Negative indexes count from the end, so at(-1) is the last character.
Spotted a mistake or missing an example? Write to us.