Sometimes, we may want to remove everything after a given character in our JavaScript string.
In this article, we’ll look at how to remove everything after a certain character in our JavaScript string.
String.prototype.split
We can split a string with the split
method.
For instance, we can write:
const url = '/Controller/Action?id=1111&value=2222'
const [path] = url.split('?')
console.log(path)
to get the path string before the question mark with split
.
split
returns an array of substrings separated by the given character.
So we can destructure the returned array and get the first item.
Therefore, path
is: '/Controller/Action’
.
String.prototype.indexOf and
String.prototype.substring
The indexOf
method lets us get the index of the given character in a string.
We can use it with the substring
method to extract the substring from the beginning to the given index returned by indexOf
.
For instance, we can write:
const url = '/Controller/Action?id=1111&value=2222'
const path = url.substring(0, url.indexOf('?'));
console.log(path)
We call url.indexOf('?')
to get the index of the question mark character.
Then we pass that into substring
as the 2nd argument.
0 as the first argument means we get the substring from the first character to the index passed in the 2nd argument.
So path
has the same value as before.
Regex Replace
We can also call the string replace
method with a regex to remove the part of the string after a given character.
For instance, we can write:
const url = '/Controller/Action?id=1111&value=2222'
const path = url.replace(/\?.*/, '');
console.log(path)
The /\?.*/
regex matches everything from the question to the end of the string.
Since we passed in an empty string as the 2nd argument, all of that will be replaced by an empty string.
replace
returns a new string with the replacement applied to it.
So path
is the same value as before.
Conclusion
There are several ways we can use to extract the part of the string after the given character with several string methods.