JavaScript, how to get string until character
By Flavio Copes
Learn how to get the part of a string before a specific character in JavaScript using split, a quick one-liner that returns everything up to that point.
I needed to get the first part of a string, everything before a specific character, -.
Here’s how I did it:
const str = 'test-hey-ho'
str.split('-')[0] //'test'
split() cuts the string into an array wherever it finds the character you pass. So 'test-hey-ho'.split('-') gives you ['test', 'hey', 'ho']. Grabbing index 0 returns the first piece, which is everything before the first -.
What if the character appears more than once?
That’s the nice part. split('-') splits on every -, but you only read the first element, so the extra dashes don’t matter. You always get the text up to the first one.
What if the character isn’t there?
split() still returns an array, just with a single item, the whole original string. So index 0 is the full string:
const str = 'hello'
str.split('-')[0] //'hello'
That’s usually the behavior you want. Nothing to guard against.
The slice alternative
There’s another way, using indexOf() and slice():
const str = 'test-hey-ho'
str.slice(0, str.indexOf('-')) //'test'
indexOf('-') finds the position of the first -, and slice() cuts from the start up to that position.
Be careful with one edge case here. If the character isn’t found, indexOf() returns -1. slice(0, -1) doesn’t return an empty string, it returns everything except the last character, which is almost never what you want:
const str = 'hello'
str.indexOf('-') //-1
str.slice(0, -1) //'hell'
So the slice() version needs an extra check when the character might be missing. That’s why I reach for split('-')[0] by default. It handles the missing case for free and reads a little cleaner. Use slice() when you specifically need the index for something else too.
Related posts about js: