Find JavaScript Substring After Character


In this brief guide, we will learn how to find the substring after a given character in a string in JavaScript using different ways.

Programmers often need to find the substring in JavaScript as a fraction of big some bigger tasks.

Let's see how to find JavaScript substring after a character.

    Table Of Contents

  1. Using substring method
  2. By splitting string
  3. Using replace method
  4. Conclusion

JavaScript Substring After Character

1. Using substring method

The substring method in JavaScript returns a part of a string between the start and end indexes.

If the end index is not specified, it will return the substring from the start index to the end of the string.

To get substring after a character, we can pass the index of that character as the start index and leave the end index as default.

Example

// javascript substring after character
var str = "Break string - at dash";

// get the substring after the dash
var substr = str.substring(str.indexOf("-") + 1);

console.log(substr); // 👉 at dash

In the above program, we have used the substring method to get the substring after the dash. To get the index of the dash, we used the indexOf() method.


2. By splitting string

The split() method in JavaScript splits a string into an array of substrings.

To get a substring after a character, we can split the string at the given character and get the second substring.

Example

// javascript substring after character
var str = "Break string - at dash";

// using split
var substr = str.split("-")[1];

console.log(substr); // 👉 at dash

After splitting the string at the dash, we get an array of substrings. i.e ["Break string "," at dash"]. To get the second substring, we used the [1] index of the array.

Using pop() method:

Example

// javascript substring after character
var str = "Break string - at dash";

// using pop()
var substr = str.split("-").pop();

console.log(substr); // 👉 at dash

The pop() method removes the last element of an array and returns it. This way we can get the substring after the dash.


3. Using replace method

The replace() method in JavaScript replaces a substring with another substring.

The idea here is to replace all the characters in the string before the given character with an empty string. This way we can get the substring after the character.

Example

// javascript substring after character
var str = "Break string - at dash";

// using replace
var substr = str.replace(/^.*-/, "");

console.log(substr); // 👉 at dash

We have used regex in the replace() method to replace all the characters in the string before the given character with an empty string.


Conclusion

We have seen 3 ways to find substring after a character in JavaScript.

The methods we looked at are:

  • substring() method
  • split() method
  • replace() method