skip to Main Content
var convertToArray = (txt) => {
  let arr = txt.split(" ");
  console.log(arr);
};

convertToArray("Hello World   ");

At the end of Hello World I have 4 spaces and now I need to take that whitespace as element of an array.

E.g.: ["Hello", "World", " "]

2

Answers


  1. You should use this code:

    var convertToArray = (txt) => {
      let arr = txt.split(/s+/); // Use regular expression to split by one or more spaces
      console.log(arr);
    };
    
    Login or Signup to reply.
  2. 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   ")
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search