How to split a string?

I have a string
word or phrase 1 | word 2 ... | word 3 etc
it is necessary to divide it as 3 variables , the delimiter is always the same they have this |
how to do it someone tell me?
March 19th 20 at 08:40
2 answers
March 19th 20 at 08:42
Solution
The split method?
let arr = str.split('|');
It will turn the array can be divided into variables through destructurization, but have fixed to define the variables
let [word1, word2 ] = 'phrase 1 | word 2'.split('|');

the rest can be hidden in an array
let [word1, word2, ...otherWords] = 'phrase 1 | phrase 2 | phrase 3'.split('|');
thanks , did so
let [word1, word2, word3 ] = 'phrase 1 | word 2 | word 3'.split('|');
console.log($.trim(word1));
console.log($.trim(word2));
 console.log($.trim(word3));
- Reba.Turcotte commented on March 19th 20 at 08:45
@Reba.Turcotte, well, either that or as below colleague wrote (there are spaces included in the split), or so
let [word1, word2, word3] = 'phrase 1 | word 2 | word 3'.split('|').map(x => x.trim());

so no copy-paste. - randall88 commented on March 19th 20 at 08:48
March 19th 20 at 08:44
Solution
const [a, b, c, ...rest] = 'foo | foo bar | foo bar baz | qux | etc'.split(' | ');

console.log(a); //"foo"
console.log(b); //"foo bar"
console.log(c); //"foo bar baz"
console.log(rest); //[ "qux", "etc" ]

Find more questions by tags JavaScript