How to Split a String by Hyphen using JavaScript

avatar

Borislav Hadzhiev

Thu Nov 18 20212 min read

Split a String by Hyphen in JavaScript #

Use the split() method to split a string by hyphen, e.g. str.split('-'). The split method takes a separator as a parameter and splits the string by the provided separator, returning an array of substrings.

index.js
const str = 'one-two-three'; const result = str.split('-'); console.log(result); // ๐Ÿ‘‰๏ธ๏ธ ['one', 'two', 'three'] const [first, second, third] = result; console.log(first); // ๐Ÿ‘‰๏ธ "one" console.log(second); // ๐Ÿ‘‰๏ธ "two" console.log(third); // ๐Ÿ‘‰๏ธ "three"

The only parameter we passed to the String.split method is the separator we want to split the string on.

The method returns an array of strings, split at each occurrence of the provided separator.

In our example, the string contains 2 hyphens, so the array has a total of 3 elements.

To assign the values of the array to variables, we used destructuring assignment.

This syntax allows us to unpack the values of the array into multiple variables, on a single line.

You could even skip a value if you don't need it.

index.js
const str = 'one-two-three'; const result = str.split('-'); // ๐Ÿ‘‡๏ธ ['one', 'two', 'three'] console.log(result); const [, , third] = result; console.log(third); // ๐Ÿ‘‰๏ธ "three"

We added 2 commas to signify that we are not interested in the first two array elements.

An alternative approach is to access the array element at the specific index.

index.js
const str = 'one-two-three'; const result = str.split('-'); console.log(result); // ๐Ÿ‘‰๏ธ๏ธ ['one', 'two', 'three'] const first = result[0]; const second = result[1]; const third = result[2]; console.log(first); // ๐Ÿ‘‰๏ธ "one" console.log(second); // ๐Ÿ‘‰๏ธ "two" console.log(third); // ๐Ÿ‘‰๏ธ "three"

We used the bracket [] notation syntax to access the array elements and assign them to variables.

Indexes are zero-based in JavaScript, meaning the first element in an array has an index of 0, and the last - an index of array.length - 1.

This approach achieves the same result as using destructuring assignment, however is a bit more verbose.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee