Search code examples
javascript

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 4 spaces and now I need to take that whitespace as element of an array.

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


Solution

  • Use String.match instead of split and filter out the single spaces. Something like:

    const convertToArray = (txt) => {
      return txt.match(/\s{1,}|\b(.+?)\b/g)?.filter(v => v !== ` `);
    };
    
    console.log(JSON.stringify(convertToArray("Hello World   ")));
    console.log(JSON.stringify(convertToArray("   Hello World   and bye again   ")));

    Note: the above will only work for words within word boundaries (letters (A–Z, a–z), numbers (0–9), and underscore (_)). When all characters in words should be included (like in "Hello World! "), feel free to use this parsing function:

    console.log(
      JSON.stringify(parseWords(`Hello World!    `)));
    console.log(
      JSON.stringify(parseWords(`Hello World! And    well... bye again!   `)));
    // including single spaces
    console.log(
      JSON.stringify(parseWords(`Hello World! And    well... bye again!   `, 1)));
    
    function parseWords(txt, includeSingleSpaces = false) {
      let result = [txt[0]];
      txt = txt.slice(1).split('');
      
      while (txt.length) {
        const last = result[result.length - 1].at(-1);
        
        if (txt[0] === ` ` && last === ` ` || txt[0] !== ` ` && last !== ` `) {
          result[result.length - 1] += txt.shift();
          continue;
        }
    
        if (last !== ` ` && txt[0] === ` ` || last === ` ` && txt[0] !== ` `) {
          result.push(txt.shift());
          continue;
        }
    
        result[result.length - 1] += txt.shift();
        result.push(txt.shift());
      }
      
      return includeSingleSpaces ? result : result.filter(v => v !== ` `);
    }