The substr() method in JavaScript and how it’s different from substring()

March 4, 2021

We saw a few examples for substring() in this post.

Let’s understand how substr() works.

substr() method in JavaScript


string.substr(from, numberOfCharacters)

Things to remember

  1. The from argument is the position you want to start the substring from and numberOfCharacters argument is the total number of characters you want to take out.
  2. from is required and numberOfCharacters is optional. If you don’t specify numberOfCharacters then it will give you the rest of the string in return from the specified starting index.
  3. First character starts at zero and if we specify from greater or equal to the number of characters in the string then it will return an empty string.
  4. If from is negative then it will use it as an index from the end of the string.


Get first 6 characters from a string using substr()

var str = "YogeshChauhan.com";
var sub = str.substr(0,6);

Get the rest of the string skipping the first 6 characters using substr()

var str = "YogeshChauhan.com";
var sub = str.substr(6);

Get the first character from the string using substr()

var str = "YogeshChauhan.com";
var sub = str.substr(0,1);

Get the last character from the string using substr()

var str = "YogeshChauhan.com";
var sub = str.substr(str.length-1,1);

The difference between substring() and substr()

The substr() method takes out parts of a string just like substring() does. The subtle difference is in the way it works and how it works.

substring() takes two arguments, start and end for the substring you want. substr() takes two arguments too and the first argument is the start of the substring as well. The only difference is the second argument we pass. In substr() we need to pass the number of characters we want in a substring.


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 horizontal scrolling menu with and without flex using CSS (or SCSS)?CSSSelf-Driving and Intelligent NetworksMiscKubernetes vs. Docker? It’s a misleading phraseMiscHow to create flickering text using CSS?CSSAccessing and Setting features of JavaScript ObjectsJavaScriptHow to add a ribbon inside a container using CSS?CSS