How can I split a JavaScript string by white space or comma?

前端 未结 6 523
遥遥无期
遥遥无期 2020-12-12 15:10

If I try

\"my, tags are, in here\".split(\" ,\")

I get the following

[ \'my, tags are, in here\' ]

Wherea

相关标签:
6条回答
  • 2020-12-12 15:47

    The suggestion to use .split(/[ ,]+/) is good, but with natural sentences sooner or later you'll end up getting empty elements in the array. e.g. ['foo', '', 'bar'].

    Which is fine if that's okay for your use case. But if you want to get rid of the empty elements you can do:

    var str = 'whatever your text is...';
    str.split(/[ ,]+/).filter(Boolean);
    
    0 讨论(0)
  • 2020-12-12 15:53
    "my, tags are, in here".split(/[ ,]+/)
    

    the result is :

    ["my", "tags", "are", "in", "here"]
    
    0 讨论(0)
  • 2020-12-12 15:54

    String.split() can also accept a regular expression:

    input.split(/[ ,]+/);
    

    This particular regex splits on a sequence of one or more commas or spaces, so that e.g. multiple consecutive spaces or a comma+space sequence do not produce empty elements in the results.

    0 讨论(0)
  • 2020-12-12 15:58

    input.split(/\s*[\s,]\s*/)

    \s* matches zero or more white space characters (not just spaces, but also tabs and newlines).

    ... [\s,] matches one white space character or one comma

    If you want to avoid blank elements from input like "foo,bar,,foobar", this will do the trick:

    input.split(/(\s*,?\s*)+/)

    The + matches one or more of the preceding character or group.

    Edit:

    Added ?after comma which matches zero or one comma.

    Edit 2:

    Turns out edit 1 was a mistake. Fixed it. Now there has to be at least one comma or one space for the expression to find a match.

    0 讨论(0)
  • 2020-12-12 16:00

    When I want to take into account extra characters like your commas (in my case each token may be entered with quotes), I'd do a string.replace() to change the other delimiters to blanks and then split on whitespace.

    0 讨论(0)
  • 2020-12-12 16:08

    you can use regex in order to catch any length of white space, and this would be like:

    var text = "hoi how     are          you";
    var arr = text.split(/\s+/);
    
    console.log(arr) // will result : ["hoi", "how", "are", "you"]
    
    console.log(arr[2]) // will result : "are" 
    
    0 讨论(0)
提交回复
热议问题