Sat Oct 09 2021·2 min read
Photo by Etienne Boulanger
To get the substring before a specific character, call the
method, passing it a start index of
0 and the character's index as parameters.
substring method will return the part of the string before the specified
const str = 'Hello World_Goodbye World'; const before_ = str.substring(0, str.indexOf('_')); console.log(before_); // 👉️ Hello World
We use the
method to get the substring before the
The parameters we pass to the method are:
0and 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
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
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.
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.
lastIndexOf method returns
-1 if the character is not contained in the
I'll send you 1 email a week with links to all of the articles I've written that week