Categories
JavaScript Answers

How to get a substring before a character with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *