JavaScriptStrings

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
On this page

Example

#
JavaScript
const lesson = 'Lesson 7: Loops'

console.log(lesson.substring(0, 6))
console.log(lesson.substring(10))
Console
Lesson
Loops

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

#
Syntax
string.substring(indexStart)
string.substring(indexStart, indexEnd)

Parameters

#
  • indexStart

    number

    The index of the first character of the result. Negative values and NaN are converted to 0.
  • indexEnd

    number, optional

    The index before which the result ends. Defaults to the string's length. If it is smaller than indexStart, the arguments are swapped.

More examples

#
Differences from slice()
JavaScript
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)
Console
Programming
ming
gram
0
Text between brackets
JavaScript
const message = 'Congratulations [Emma], module complete!'
const start = message.indexOf('[') + 1
const end = message.indexOf(']')

console.log(message.substring(start, end))
Console
Emma

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

#

Spotted a mistake or missing an example? Write to us.