Javascript Substring Method (with Example)

In this tutorial, you will learn about one of the most used javascript string substring() method. It is a string method that returns a specific part of the string between the start and end indexes.

Javascript substring() Method


const message = "codingclaw is a blog";

//it will return the substring from index 0 to 10;
let result = message.substring(0, 10);

// Output: codingclaw


Here is the syntax of the javascript substring() method.


Here str is a string.

substring() parameters

The javascript substring() method takes in two parameters.

StartIndex: it is the index from where you want to start creating a substring.

EndIndex: This is the index up to where you want to include the current string portion in the substring (optional).

Note :
• If the value you passed as the index is less than 0 then it would be treated as 0.
• If the value you passed as the index is greater than the string.length then it would be treated as string.length.
• If StartIndex is greater than the EndIndex then both index will be swapped.

substring() return value

substring() methods return the specific portion of a string.

Note: it does not change the original string.

Example 1: How to use substring()

let string = "codingclaw is a blog";

// first character
substr1 = string.substring(0, 1);
console.log(substr1); // c

// if start > end, they are swapped
substr2 = string.substring(1, 0);
console.log(substr2); // c

// From 11th to last character
substr3 = string.substring(10);
console.log(substr3); // is a blog

// the extreme values are 0 and str.length

// same as string.substring(0)
substr4 = string.substring(-44, 90);
console.log(substr4); // codingclaw is a blog

// indexEnd is exclusive
substr5 = string.substring(0, string.length - 1);
console.log(substr5); // codingclaw is a blo

So, this was the complete tutorial on the javascript substring() method. Hope you will understand the concept behind this method. If you still have any queries regarding the javascript string substring() method then you can ask me in the comments.

Leave a Comment

Your email address will not be published. Required fields are marked *