YogeshChauhan . com

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

amazon

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 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

What is iFrame in HTML? Why do we need it?HTMLSQL Right JoinSQL/MySQLAggregate Functions Examples in Postgres for BeginnersPostgresHow to add a Pie Chart in Angular App?AngularHow SCSS (Sass) finds a module without a file extension?SCSSSorting Arrays in JavaScriptJavaScript