var convertToArray = (txt) => {
let arr = txt.split(" ");
console.log(arr);
};
convertToArray("Hello World ");
at the end of Hello World I have taken 4 spaces and now I need to take that space as element of an array
eg: ["Hello", "World", " " ] – (last element 4 spaces)
>Solution :
Use match instead of split and filter out the single spaces. Something like:
var convertToArray = (txt) => {
let arr = txt.match(/\b(.+?)\b|\s{2,}/g)?.filter(v => v !== ` `);
console.log(JSON.stringify(arr));
};
convertToArray("Hello World ");
convertToArray(" Hello World And Bye again ")