Splitting string by whitespace, without empty elements?

前端 未结 5 1383
北荒
北荒 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 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"]
    

提交回复
热议问题