Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to check the whitespace in string and convert it into array – Javascript

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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   ")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading