Get the Substring before a specific Character in JavaScript

avatar

Borislav Hadzhiev

Sat Oct 09 20212 min read

Get Substring before a specific Character #

To get the substring before a specific character, call the substring() method, passing it a start index of 0 and the character's index as parameters. The substring method will return the part of the string before the specified character.

index.js
const str = 'Hello World_Goodbye World'; const before_ = str.substring(0, str.indexOf('_')); console.log(before_); // ๐Ÿ‘‰๏ธ Hello World

We use the String.substring method to get the substring before the _ character.

The parameters we pass to the method are:

  1. the start index - the index of the first character to be included in the returned string
  2. the end index - go up to, but not including this index
Indexes are zero-based in JavaScript, which means that the first index in a string is 0 and the last is str.length - 1.

To get the index of the specific character, we use the String.indexOf method.

If the character is not contained in the string, the indexOf method returns -1.

In this case the substring method would get invoked with (0, -1) and return an empty string, because the substring method treats negative values as if you passed 0.

There might be a scenario where you have multiple occurrences of the specific character and you want to get the substring before the last occurrence.

In this case, use the lastIndexOf method to locate the index of the last occurrence of the character.

index.js
const str = 'Hello_World_Goodbye_World'; const beforeLast_ = str.substring(0, str.lastIndexOf('_')); console.log(beforeLast_); // ๐Ÿ‘‰๏ธ Hello_World_Goodbye

The String.lastIndexOf method returns the index of the last occurrence of the character.

The lastIndexOf method returns -1 if the character is not contained in the string.

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