Splitting string by whitespace, without empty elements?

前端 未结 5 1376
北荒
北荒 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: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.

提交回复
热议问题