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

前端 未结 4 1906
陌清茗
陌清茗 2020-12-01 09:54

I typically use the following code in JavaScript to split a string by whitespace.

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


        
相关标签:
4条回答
  • 2020-12-01 10:30

    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)
    
    0 讨论(0)
  • 2020-12-01 10:40

    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) || []
    
    0 讨论(0)
  • 2020-12-01 10:46

    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)
               {
                  newArr.push(element);
               }
           }
           const NumberOfWords = newArr.length;
    
           return NumberOfWords;
       }
    
    0 讨论(0)
  • 2020-12-01 10:53

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

    0 讨论(0)
提交回复
热议问题