Borislav Hadzhiev
Thu Oct 14 2021·3 min read
Photo by Roberto Nickson
To remove everything after a specific character in a string:
split()
method on the string, passing it the character as a
parameter.split
method returns an array containing two substrings, split on the
provided character.0
to get everything before the character.const str = 'BMW[1996]'; const removed = str.split('[')[0]; console.log(removed); // 👉️ BMW
We use the
String.split
method to split on the bracket [
character.
The split method returns an array of 2 substrings, split on the supplied character.
const str = 'BMW[1996]'; const split = str.split('['); console.log(split) // 👉️ ['BMW', '1996]'
We only need the substring before the specified character, so we access the
array at index 0
.
An alternative approach is to use the slice
method.
To remove everything after a specific character in a string:
slice()
method passing it a starting index of 0
and an end index
equal to the character's index in the string.slice
method returns a new string containing a part of the original
string.const str = 'BMW[1996]'; const removed = str.slice(0, str.indexOf('[')); console.log(removed); // BMW
We pass the following parameters to the String.slice method:
The
String.indexOf
method returns the index of the provided character in the string or -1
if the
character was not found in the string.
indexOf
method might return -1
. Passing -1
as the second parameter to the slice
method would cause a bug in the application.If you're unsure, whether the string contains the specific character, use an
if
statement to verify.
let removed; const index = str.indexOf('['); if (index !== -1) { removed = str.slice(0, index); } console.log(removed); // 👉️ BMW
In the code snippet we only assign a string to the removed
variable if we're
sure that the character was found in the string.
indexOf
method returns the index of the first occurrence of a character in the string. If you need to remove everything after the last occurrence of a specific character, use the lastIndexOf
method instead.const str = 'BMW[abc][1996]'; const removed = str.slice(0, str.lastIndexOf('[')); console.log(removed); // 👉️ BMW[abc]
We have two sets of brackets in our string and we only want to remove everything after the last set of brackets.
The
String.lastIndexOf
method returns the index of the last occurrence of the provided character or
-1
if the character is not contained in the string.