Yogesh Chauhan's Blog

substring() Method in JavaScript

in JavaScript on March 3, 2021

We can use the substring() method to extract characters from a string.

It takes two arguments, start and end for the substring you want. It does NOT include the end character.

If you pass the start parameter which is greater than the end parameter then JS will act smart and will swap the parameters.

This method does NOT change the original string but returns a new small(sub) string.

substring() Method syntax


str.substring(from, to)

from argument is the first character to start the substring from and the to argument is the character before the substring ends.

from is required and to is optional.

If you don’t specify the to argument then it will cut the string from the specified from to the end of the string.

It’s a but confusing as why would you want the the first specified character to include and the second one to exclude! But that’s the way it is.

substring() Method return value

substring() method returns a substring. It doesn’t modify the main string.

substring() Method Examples

How to get the first 6 characters from a string?


var str = "YogeshChauhan.com";
var sub = str.substring(0, 6);
console.log(sub);
//Yogesh

How to get the rest of the string skipping the first 6 characters?


var str = "YogeshChauhan.com";
var sub = str.substring(6);
console.log(sub);
//Chauhan.com

How to get the first character from a string?


var str = "YogeshChauhan.com";
var sub = str.substring(0, 1);
console.log(sub);
//Y

How to get the last character from a string?


var str = "YogeshChauhan.com";
var sub = str.substring(str.length - 1, str.length);
console.log(sub);
//m

How to get the last 3 characters from a string?


var str = "YogeshChauhan.com";
var sub = str.substring(str.length - 3);
console.log(sub);
//com


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
Is there a difference between SCSS and Sass?SCSSHow to select multiple values in React dropdown?ReactCan we execute conditions in SQL?SQL/MySQLHow to check if a link has http or https in it in JavaScript?JavaScriptCrypto.getRandomValues() method in JavaScriptJavaScriptHow to check if radio button is checked or not using JavaScript?JavaScript