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 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
WordPress: How to add a Search Icon in Menus with toggle effect using jQuery?jQueryHow to create a for loop in SCSS (Sass)?SCSSWP_Query Class in WordPressWordPressHow to update database configurations in WordPress?WordPressSafe Practice to add Links to cross-origin destinationUI/UXWhat are Controlled Components in React?React