Browse by Domains

What is a Javascript Substring? Variants, Uses and more

What is a string?

A string is a collection of a series of characters that is used to represent text. For example: “Hello World”.

What is a Substring in Javascript?

A substring is a small part of a string or a subset of a string. A substring is a contiguous sequence of characters in a string. For example: “Hello” is a substring of the string “Hello World”. 

Substring in Javascript is an inbuilt function that is commonly used to return a part of a given string that can be used to create smaller strings from the bigger string. Javascript’s strings are immutable, i.e., the original string remains the same, and the method returns a new string every time. It doesn’t edit or make changes to the original string. 

The Substring(int startIndex, int endIndex) method returns a new string which is a substring of that input string we provided between the start index and end index with the indexes starting from zero(0). 

In simple language, when we provide any string or a complete sentence, it simply returns a part of that sentence, whether it is a word or a combination of some words from that sentence or string. The substring method starts at the specified index number, and the method finds the character at that index number and returns it upto the ending index number, which we provided as parameters in our method. 

The reason behind its use is that it creates smaller strings from larger strings. As we know that strings are immutable, and the original string remains the same as it is but the substring methods that we use to return a new string and the old or input string remain the same. 

Syntax:

String.substring(start_index, end_index)

Substring parameters start_index and end_index define the part of the string that is taken as a substring. The end_index can be optional. 

This method returns a new string that is part of the given string. 

Variants of Substring in Javascript:

We have two variants of the substring() method in Javascript, which are described below:

  1. Variant 1:

Given the start index the returned substring includes​ characters starting from the specified start index of the input string, until the end of the string.

string.substring(var startIndex)

For example:

<!DOCTYPE html>
<html>
  <head>
<title> Variants of substring in javascript</title>
    </head>
<body>
<p>Click to get the substring out of 'Hello World'.</p>
<script>
  function myFunc() {
  var str = "Hello World";
  var substr = str.substring(3);
  document.getElementById("demo").innerHTML = substr;
}
</script>
<button onclick="myFunc()">Try Me!</button>
<p id="demo"></p>
</body>
</html>

Output: lo World

As the index starts with 0, Hel takes index 0,1,2, and the output is displayed starting from index 3, as mentioned in the start index of the substring.

  1. Variant 2:

Here we specify both the start index and the end index. The returned substring will have characters including and between the given indexes. The character at the start index is included in the substring, and the character at the end index is excluded. So, the characters in the extracted substring begin from the start index till the end index-1.

string.substring(var startIndex, var endIndex)

For example:

<!DOCTYPE html>
<html>
<head>
<title> Variants of substring in javascript</title>
    	</head>
<body>
<p>Click to get the substring out of 'Hello World'.</p>
<script>
  function myFunc() {
  var str = "Hello World";
  var substr = str.substring(1,6);
  document.getElementById("demo").innerHTML = substr;
}
  </script>
<button onclick="myFunc()">Try Me!</button>
<p id="demo"></p>
</body>
</html>

Output: ello. 

The start index and end index are given. hence the resultant substring begins with the start index and  ends with index-1

Use and Applications of Substring:

Substring in javascript is a string manipulation function that can manipulate all string data types such as BIT, CHARACTER, and BLOB and can extract characters from a string and create a new string. It has many applications, such as suffix and prefix extraction.

  • Let us take an example if you want to extract a name from a string of text or the last name from a given string. You can do all this by the use of the Substring method in Javascript. The demonstration of this example in code is below:
<script>
 	var str = "Hello World";
var substr = str.substring(4);
  	console.log(“The original string is:”);
console.log(substr);
</script>

Output:

The original string is: Hello World

The extracted substring is: o World

  • The Substring method is also useful to check if a given string is palindrome or not such that the Substring method reads the string the same way from both ends. To better understand, see the example below:

Javascript function to check if the string is palindrome or not.

function checkPalin(string) {
    // string.length is used to find the length of a string
    const len = string.length;
    // looping through half of the string
    for (let i = 0; i < len / 2; i++) {
    // her we are checking if first and last string are same
        if (string[i] !== string[len - 1 - i]) {
            return 'String is not a palindrome';
        }
    }
    return 'String is a palindrome';
}
// take input from user
const string = prompt('Enter a string to check for palindrome: ');

// function call
const value = checkPalin(string);
console.log(value);

Output:

Enter a string: Hello

String is not a palindrome

  • The substring method is very useful for getting all substrings of a string. 

The javascript code is as follows:

<script>
        // This function will print all substring from a given string
        function SubString( stri , n)
        {
        for (var i = 0; i < n; i++)
            for (var j = i+1; j <= n; j++)
            document.write(stri.substring(i, j)+"<br/>");
        }
            var stri = "abcd";
            SubString(stri, stri.length);
</script>

Output:

a

ab

abc

abcd

b

bc

bcd

c

cd

d

How to use Substring with length Property in JavaScript:

The length property in javascript is used to get the length of a string. The substring() method of javascript and length property are used together to extract the last characters of a particular string. This  inbuilt method is easier to remember and use as you don’t need to know the starting and ending indices.

Let us see an example below to understand better how it can be used:

Example:

var theString = “GreatLearning”;
var theString1 = theString.substring(theString.length – 8 ); // Displays last 8 characters of theString “GreatLearning”
console.log(theString1);

OUTPUT:

Learning

In the above example, we didn’t need to enter the starting and ending index of the string, and we just entered the length of the substring that we needed in our result. So it returned 8 characters, and it returned the substring from the end as we used the (-) sign before 8 while specifying parameters. 

substring() vs substr() in JavaScript.

The difference between the substring() and substr() JavaScript string methods is that substring() takes a starting index and an end index, while substr takes only a starting index and a length of characters.

String.prototype.substring

The substring() method returns a new string which is a subset of the actual string. Takes up one or two arguments. With one argument given, we get the string starting from the specified index (inclusive) until the end of the string:

const myStr = 'Learning';

const myNewStr = myStr.substring(2);

console.log(myNewStr); 

OUTPUT:

arning

With two arguments given, we get a subset of the string from the starting index to the end index (exclusive):

const myString = 'Learning';

const myNewStr = myString.substring(0, 3);

console.log(myNewStr);

Output:

Lea

String.prototype.substr

The substr() method is very similar, but the second argument is for the number of characters and not for the end index.

Here we want a 4-character string from a starting index of 3:

const myString = 'GreatLearning';

const myNewStr = myString.substr(3, 4);

console.log(myNewStr); 

OUTPUT: atLe

Negative start index

The first argument to substr can take up a negative integer. In this case, the start of the returned string is counted from the end of the string that the method is used on:

const myString = 'LearningAlligator';

const myNewStr = myString.substr(-3);

console.log(myNewStr); 

Output:

gni

Same Result When Only One Argument

If only one positive integer is used as an argument, then both substring and substr return the same value:

const myString = 'GreartLearning';

const myNewSubstring = myString.substring(4);

const myNewSubstr = myString.substr(4);

console.log(myNewSubstring); 

console.log(myNewSubstr); 

Output:

rtLearning

rtLearning

slice( ) Method

The slice( ) method is similar to the substring( ) method, and it returns a substring of the original string. The slice method takes two arguments

SYNTAX:

string.slice(startIndex, endIndex);

Where:

startIndex: refers to the starting point of the substring

endIndex: refers to the ending point of the substring (optional)

The commonalities between substring( ) and slice( ) methods:

  • If we don’t give the ending index, then we get a substring starting from the given index number until the end of the original string
  • If we give both the startIndex and the endIndex, then we will get the characters between the given index numbers of the original string.
  • If startIndex and endIndex are greater than the length of the string, it returns an empty string.

Differences of the slice( ) method:

  • If startIndex is greater than the endIndex, the slice( ) method returns an empty string.
  • If startIndex is given a negative number, then the first character begins from the end of the string, i.e., the reverse of the string.

Note: We can use the slice( ) method also for JavaScript arrays. You can find here my other article about the slice method to see the usage for arrays.

Important Points on JavaScript subString: 

  • The JavaScript substring() method extracts the symbols between two indexes and returns a data string which is a subset of the original string.
  • substring() method extracts the symbols in a string between end and start and does not include the end itself.
  • If the end index has a smaller value than the start, the arguments will be switched.
  • If either the end index or start index is given as a negative number, the value is 0.
  • The original string remains unchanged after using the substring() method.

Here are some examples that you can try yourself to understand the concept of JavaScript SubString completely:

<html>
   <head>
      <title>Great Learning JavaScript String substring() Method</title>
   </head>
   
   <body>   
      <script type = "text/javascript">
        var string = "Apples are red or green in color and round";    
        document.write("(4): "    + string.substring(4));   
        document.write("<br />");  
        document.write("(2,3): "    + string.substring(2,3));
        document.write("<br />(0,8): "   + string.substring(0, 8));
        document.write("<br />(-5): "      + string.substring(-5));
        document.write("<br />");
        document.write("(2,3): "    + string.slice(2,3));
     </script>
   </body>
</html>

OUTPUT:

(4): es are red or green in color and round

(2,3): p

(0,8): Apples a

(-5): Apples are red or green in color and round

(2,3): p

Conclusion:

Examining and manipulating is a common task performed by most programming languages, especially with user-facing code. For various reasons, such as validating strings, you’ll need to check if a string contains a substring. There are 3 different methods, substring(), substr(), and slice(), provided by Javascript that allows us to validate a string and extract what is required without changing the original string.

Avatar photo
Great Learning
Great Learning's Blog covers the latest developments and innovations in technology that can be leveraged to build rewarding careers. You'll find career guides, tech tutorials and industry news to keep yourself updated with the fast-changing world of tech and business.

Leave a Comment

Your email address will not be published. Required fields are marked *

Great Learning Free Online Courses
Scroll to Top