Difference between .split(/\s+/) and .split(“ ”)?

前端 未结 3 1890
伪装坚强ぢ
伪装坚强ぢ 2021-02-15 11:22

:) First of all, sorry my bady english :p I was taking a look to the next js code fragment:

var classes = element.className.split(/\\s+/);

That c

3条回答
  •  Happy的楠姐
    2021-02-15 11:32

    \s captures more types of whitespace than space

    From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions:

    Matches a single white space character, including space, tab, form feed, line feed. Equivalent to [ \f\n\r\t\v​\u00a0\u1680​\u180e\u2000​\u2001\u2002​\u2003\u2004​\u2005\u2006​\u2007\u2008​\u2009\u200a​\u2028\u2029​​\u202f\u205f​\u3000].

    Also the + means it will match on multiple spaces. So foo bar will produce a different result:

    js> 'foo      bar'.split(' ')
    ["foo", "", "", "", "", "", "bar"]
    js> 'foo      bar'.split(/\s+/)
    ["foo", "bar"]
    

提交回复
热议问题