Tutorials Tonight
Follow Us

Substring In JavaScipt - Get Substring From String


In this tutorial, you will learn about substrings and how to extract a substring from a string in javascript using substr(), substring() and slice() method.


Let's first understand about substring then we will look at different ways to get the substring.

What Is Substring?

A substring is a sequence of characters within a string. It is to be noted that only a sequence of characters is considered to be a substring not a subsequence of characters.

In simple word you can say a substring is a part of an original string having the same sequence of character as the original string.

For the string "code" list of all substrings would be "code", "cod", "ode", "co", "od", "de", "c", "o", "d" and "e".

string and it's substrings

The above image is a visual representation of the above list of substrings.


1. substr Javascript method to get substring of desired length

The substr() method is used to extract a substring from a string. It returns a part of the string starting from a given index up to a specified number of characters afterwards.

Example

const sentence = "Learning to code";

const subString = sentence.substr(4)
console.log(subString);
▶ Try It

In the above example, the substr method extracts a substring from the original string from index 20 to the end of the string.

Syntax of substr() method

The syntax of substr() method is:

string.substr(startIndex [ ,length]);
  1. startIndex - It is the first parameter of the method which determines the index in the original string from where the substring is to be extracted.
    • If startIndex is a negative number index is counted from the end of the string.
    • If startIndex is NaN then it is treated as 0.
  2. length (optional) - This is an optional parameter that determines the length of character to be included in the substring.
    • If length is omitted or is undefined then substr() method extracts characters to the end of the original string.
    • If the length given is negative or NaN (Not a Number) then it is treated as 0.

Up to this, we have understood the substr method and both its parameters, let's now look at some example to see theory in action.

Here are few examples of getting substring from a string using substr method.

# Example 1: Setting length of substring

The second parameter length specifies the length of the substring to be extracted using substr() method.

Example

const sentence = "Learning to code";
// start index is 1, length is 10
const subString = sentence.substr(1, 10);
console.log(subString);
▶ Try It

The above example set the length of the substring to 20. Now let's see what is the behaviour of substr() method at different length values.

Example

const sentence = "Learning to code";

const sub1 = sentence.substr(2, 0); // ''
const sub2 = sentence.substr(5, undefined); // return characters upto the end
const sub3 = sentence.substr(10, NaN); // ''
const sub4 = sentence.substr(1, Infinity); // return characters upto the end
const sub5 = sentence.substr(4, -5); // ''
console.log(sub1);
console.log(sub2);
console.log(sub3);
console.log(sub4);
console.log(sub5);
▶ Try It

# Example 2: Different values of startIndex

The startIndex determines from which index does substr method starts extracting the substring.

We will look at all kind of value we can provide as startIndex and see the result.

Example

const sentence = "Learning to code";

const sub1 = sentence.substr(1); // from index 1 to the end
const sub2 = sentence.substr(-15); // counting 15 position from end to the end of string
const sub3 = sentence.substr(undefined); // complete string
const sub4 = sentence.substr(Infinity); // empty string
const sub5 = sentence.substr(NaN); // complete string
console.log(sub1);
console.log(sub2);
console.log(sub3);
console.log(sub4);
console.log(sub5);
▶ Try It

2. substring Javascript method to get substring between 2 indexes

The substring() method is another built-in method in javascript to get a substring from another string.

It returns the part of the original string between 2 desired index value generally known as the start and end index.

Example

const sentence = "Learning to code";

const subString = sentence.substring(2, 5);
console.log(subString);
▶ Try It

Syntax of substring() method

The syntax of substring() method is:

string.substring(startIndex [ ,endIndex]);

Now we will see examples to get substring using the substring() method.

# Example 1: Getting characters between 2 indexes

Example

const sentence = "Learning to code";

const sub1 = sentence.substring(4, 10);
const sub2 = sentence.substring(2, 8);
console.log(sub1);
console.log(sub2);
▶ Try It

# Example 2: Swapping value of arguments

When you use arguments where startIndex is less than endIndex, then values are swapped.

Example

const sentence = "Learning to code";

// return 'earn'
const sub1 = sentence.substring(1, 5);
const sub2 = sentence.substring(5, 1);
console.log(sub1);
console.log(sub2);
▶ Try It

# Example 3: Omitting second parameter

If you omit the second parameter endIndex then the substring() method includes the character at the end of the string.

Example

const sentence = "Learning to code";

// Omitting second parameter
const sub1 = sentence.substring(2);
const sub2 = sentence.substring(5);
console.log(sub1);
console.log(sub2);
▶ Try It

# Example 4: Create copy of string omit both parameters

When both parameters of the substring() method are omitted then it returns a copy of the string as a substring.

Example

const sentence = "Learning to code";

// Omitting both parameters
const subString = sentence.substring();
console.log(subString);
▶ Try It

3. Substring slice Method

javascript slice method can also be used to extract a substring from a string. It also has 2 parameter startIndex and the endIndex same as the substring() method.

Example

let str = "Learning to code";

console.log(str.slice(2, 10));
console.log(str.slice(5, 10));
▶ Try It

Getting all substrings from a string

Let's use the above method to get all possible substrings from a string and print them using both of above mensioned methods. We will also count the number of substrings created.

Using substr() Method

First, we will use substr() method which has 2 parameters startIndex and length of the substring.

To get all substrings we will loop through the given string and use its index value and check all possible length of a substring starting from that index. For example, fixing at index 0 we will get all substring starting from 0 of any length, then increase index to 1 and get all substring again and so on.

Example

const sentence = "Learning to code";
// print all possible substrings
let count = 0;
for (let index = 0; index < sentence.length; index++) {
  for (let len = 1; len <= sentence.length - index; len++) {
    console.log(sentence.substr(index, len));
    count++;
  }
}
console.log(count);
▶ Try It

Using substring() Method

By controlling the startIndex and endIndex in the substring() method we can print all possible substrings. Fix startIndex and iterate endIndex from the current value to the last index of the string, the increase startIndex by 1 and do the same.

Look at the code below to understand.

Example

const sentence = "Learning to code";
// print all possible substrings
let count = 0;
for (let startIndex = 0; startIndex <= sentence.length; startIndex++) {
  for (let endIndex = startIndex + 1; endIndex <= sentence.length; endIndex++) {
    console.log(sentence.substring(startIndex, endIndex));
    count++;
  }
}
console.log(count);
▶ Try It

Difference between substring() and slice() method

You must be aware of the slice() method which is almost identical to the substring() method, but there some difference between them:

Points to remember:

  1. A substring is a part of a string whose characters are in the same sequence as the original string.
  2. substr() method is used to extract a substring from a string that can take the length of the substring as input.
  3. substring() method is used to extract a substring from a string take startIndex and endIndex as input.

Follow Us

Copyright © Tutorials Tonight. All Rights Are Reserved.