Borislav Hadzhiev
Thu Nov 18 2021·2 min read
Photo by Alexander Popov
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.
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.
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.
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.
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.