How to get a substring before a character with JavaScript?

Sometimes, we want to get a substring before a character with JavaScript.

In this article, we’ll look at how to get a substring before a character with JavaScript.

How to get a substring before a character with JavaScript?

To get a substring before a character with JavaScript, we can use the string’s split method.

For instance, we write:

const string = "foo-bar-baz"
const [foo] = string.split('-')
console.log(foo)

to call string.split with '-‘ to split the string by the dashes into a string array.

Then we get the word before the first dash with destructuring and assign it to foo.

Therefore, foo is 'foo'.

Conclusion

To get a substring before a character with JavaScript, we can use the string’s split method.