Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
html
substring

How to get a substring in JavaScript

Educative Answers Team

The substring() method in JavaScript returns a portion of a string and is used to get substrings.

There are two variants for substring() method implementation in JavaScript.

Variant 1

We specify a start index and the returned substring includes​ characters starting from the specified start index of the input string, until the end of the string.

stringName.substring(var startIndex)

A visualization​ of this is shown below:

1 of 3
Console

You can edit the code, written between the <script> </script> tags above and see how the output changes.

Variant 2

We specify the start index and the end index. The returned substring includes characters including and between the specified indexes. The character at the start index is included in the substring, however, the character at the end index is not. So, the characters in the extracted substring begin from the start index till the end index-1.

stringName.substring(var startIndex, var endIndex)

A visualization of this is shown below:​

1 of 3
Console

You can edit the code, written between the <script> </script> tags above and see how the output changes.

Note: substring() method does not change the original string.

Application of substrings

Substring extraction is useful for prefix and suffix extraction. For example, it is helpful in extracting the family name from a name.

RELATED TAGS

javascript
html
substring
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring