YogeshChauhan.com

substring() Method in JavaScript

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

dreamhost

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 uninstall Cocoapods from the Mac OS? #4 How to Use SQL MAX() Function with Dates? #5 How to add Read More Read Less Button using JavaScript? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Apr 7 Solution for “Yarn build: Failed because of a stylelint error” Apr 7 Make sure your links have descriptive text Apr 7 How to add Laravel to WordPress using Sage theme (and install Tailwind CSS)? Apr 2 How to create a sidebar using pure CSS? Apr 1 How to switch dark and light themes using pure CSS? Apr 1 How to calculate elapsed time in JavaScript?

You might also like these

How to create a sidebar using pure CSS?CSSHow to change perception and behavior of a person for acceptance of new systems?MiscStyling Lists with CSSCSSCSS Attribute SelectorsCSSLearn to create profile card using HTML and CSSCSSEverything you need to know about ANY, SOME and ALL Operators in PostgresPostgres