Get the Substring after a specific Character in JavaScript


Borislav Hadzhiev

Sat Oct 09 20211 min read


Photo by Ranah Malberg

Get the substring after a specific Character #

To get the substring after a specific character, call the substring() method, passing it the index after the character's index as a parameter. The substring method will return the part of the string after the specified character.

const str = 'A very_long string'; const after_ = str.substring(str.indexOf('_') + 1); console.log(after_); // ๐Ÿ‘‰๏ธ long string

In the code snippet, we use the String.substring method to get a part of the string.

The parameter we pass to the substring method is:

  • the start index - the index of the first character to be included in the returned string

We use the String.indexOf method to get the index of the first occurrence of a specific character.

However, we don't want to include the character in the returned string, so we increment its index by 1.

Note that the indexOf method returns -1 if the string does not contain the specified character.

In the case of the code snippet, if the indexOf method returns -1, we would add 1 to it and call the substring method with a starting index of 0, which would return the entire string.

Indexes are zero-based in JavaScript, therefore the index of the first character in the string is 0 and the index of the last character str.length - 1.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee