How do I split a string by whitespace and ignoring leading and trailing whitespace into an array of words using a regular expression?

点点圈 提交于 2019-11-27 20:20:49
kennebec

If you are more interested in the bits that are not whitespace, you can match the non-whitespace instead of splitting on whitespace.

"  The quick brown fox jumps over the lazy dog. ".match(/\S+/g);

Note that the following returns null:

"   ".match(/\S+/g)

So the best pattern to learn is:

str.match(/\S+/g) || []

" The quick brown fox jumps over the lazy dog. ".trim().split(/\s+/);

Instead of splitting at whitespace sequences, you could match any non-whitespace sequences:

"  The quick brown fox jumps over the lazy dog. ".match(/\S+/g)
aris

Not elegant as others code but very easy to understand:

    countWords(valOf)
    {
        newArr[];
        let str = valOf;
        let arr = str.split(" ");

        for (let index = 0; index < arr.length; index++) 
       {
           const element = arr[index];
           if(element)
           {
              this.newArr.push(element);
           }
       }
       this.NumberOfWords = this.newArr.length;

       return this.NumberOfWords;
   }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!