JavaScript substring: The Complete Guide

The substring() method extracts characters from start to end. The substring() method does not change the original string.

JavaScript substring

JavaScript substring() is a built-in string function that returns a part of the string between the start and end indexes or to the end of a string. The substring() extracts characters from indexStart up to but not including indexStart. If an indexEnd is omitted, then the substring() extracts characters to the end of a string. If an indexStart is equal to the indexEnd, then the substring() returns an empty string.

Syntax

The syntax for the javascript string substring() method is the following.

string.substring(indexStart,indexEnd)

Parameters

The indexStart parameter is required and is where to start the extraction. The first character is at index 0.

The indexEnd parameter is optional and is the position where to end the extraction. If omitted, it extracts the rest of the string.

Example

The example is the following.

// app.js

let str = 'Obama was US president';
let newstr = str.substring(0,5);
console.log(newstr);

In the above example, we get the substring’s starting index of 0 and go to 5. So the substring() becomes the Obama.

Output

Javascript String SubString Example | String.prototype.substring() Tutorial

The substring with a length property

The below example uses a substring() method and the length property to extract the last characters from a particular string.

// app.js

let str = 'Obama was US president';
let newstr = str.substring(str.length-10);
console.log(newstr);

Output

String.prototype.substring() Tutorial

If we do not specify the second parameter

Let us take a scenario where we do not specify the indexEnd and see what the output will be.

// app.js

let str = 'Obama was US president';
let newstr = str.substring(5);
console.log(newstr);

Output

Javascript String SubString Example

Any argument value that is less than 0 or greater than the length of a string is treated as if it were 0 and stringName.length, respectively. 

Any argument value that is NaN is treated as if it were 0.

That’s it for this tutorial.

Related posts

JavaScript String search

JavaScript String indexOf

JavaScript String valueOf

1 thought on “JavaScript substring: The Complete Guide”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.