Explanation
Using destructuring, String#match and Array#reduce
.match(/(?!\n).+/g)
To get an array of each line.
For each line, split it with ---
and update the accumolator (a
) and return it.
.reduce((a,c)=>{
const [key, value] = c.split("---");
a[key]=value;
return a;
}, {});
Solution
const data = `
STORY 01---abc
STORY 02---def
STORY 03---ghi
`;
const res = data.trim()
.match(/(?!\n).+/g)
.reduce((a,c)=>{
const [key, value] = c.split("---");
a[key]=value;
return a;
}, {});
console.log(res);
Recommendation
I would re-organize the final output differently since your key has a space. Also taking input directly from the textarea and using it as a key is prone to user input errors.
const data = `
STORY 01---abc
STORY 02---def
STORY 03---ghi
`;
const res = data.trim()
.match(/(?!\n).+/g)
.map(c=>{
const [key, value] = c.split("---");
return {key, value};
});
console.log(res);