AppDividend
Latest Code Tutorials

Javascript String SubString: How to Get SubString in JS

1

The substring() extracts characters from indexStart up to but not including indexStart in particular. 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.

Javascript String substring()

Javascript string substring() is an inbuilt function that returns a part of the string between the start and end indexes, or to the end of a string.

Syntax

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

string.substring(indexStart,indexEnd)

Parameters

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

The indexEnd parameter is optional, and it 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 are getting the substring’s starting index 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 will be the output.

// 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.

Finally, Javascript String substring() is over.

1 Comment
  1. dipti says

    very well coding but please one request add php demo also with angular 6 upload file

Leave A Reply

Your email address will not be published.

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