Splitting string by whitespace, without empty elements?

前端 未结 5 1372
北荒
北荒 2020-12-24 12:23

I am trying to explode an string using javascript to pick searchterms, whitespace-separated. However I get empty array elements if a searchterm is ended by a whitespace, as

相关标签:
5条回答
  • 2020-12-24 12:42

    If you want a function that you can use, just extend String:

     String.prototype.splitNoSpaces = function(){
         return this.split(' ').filter(function(i){return i});
     };
    
     //Now use it!
     var classString = "class1    class2 class3    class4";
     var classArray = classString.splitNoSpaces();
    
     //classArray[0] is class1
     //classArray[1] is class2
     //classArray[2] is class3
     //classArray[3] is class4
    

    Thanks to @user1079877 for the hint

    0 讨论(0)
  • 2020-12-24 12:46

    This is a bit old, but for documentation purposes there is also another neat way.

    someString.filter(Boolean);
    
    // Example
    ['fds', '', 'aaaaa', 'AA', 'ffDs', "", 'd'].filter(Boolean);
    // Output
    ["fds", "aaaaa", "AA", "ffDs", "d"]
    
    0 讨论(0)
  • 2020-12-24 12:56

    No matter what splitter this always works:

    str.split(' ').filter(function(i){return i})
    // With ES6
    str.split(' ').filter(i => i)
    

    Filter logic also can change in some other cases.

    0 讨论(0)
  • 2020-12-24 13:01

    You could simply match all non-space character sequences:

    str.match(/[^ ]+/g)
    
    0 讨论(0)
  • 2020-12-24 13:02

    Add function:

    //Some browsers support trim so we check for that first
    if(!String.prototype.trim) {  
      String.prototype.trim = function () {  
        return this.replace(/^\s+|\s+$/g,'');  
      };  
    }
    

    Then call trim on the string:

    var strb = "searchterm1 "; // Note the ending whitespace
    console.log(strb.trim().split(" ")); // ["searchterm1"]
    
    0 讨论(0)
提交回复
热议问题