remove unwanted commas in JavaScript

后端 未结 9 1597
青春惊慌失措
青春惊慌失措 2020-12-14 13:14

I want to remove all unnecessary commas from the start/end of the string.

eg; google, yahoo,, , should become google, yahoo.

If pos

相关标签:
9条回答
  • 2020-12-14 13:54

    match() is much better tool for this than replace()

     str  = "    aa,   bb,,   cc  , dd,,,";
     newStr = str.match(/[^\s,]+/g).join(",")
     alert("[" + newStr + "]")
    
    0 讨论(0)
  • 2020-12-14 13:55

    You should be able to use only one replace call:

    /^( *, *)+|(, *(?=,|$))+/g
    

    Test:

    'google, yahoo,, ,'.replace(/^( *, *)+|(, *(?=,|$))+/g, '');
    "google, yahoo"
    ',google,, , yahoo,, ,'.replace(/^( *, *)+|(, *(?=,|$))+/g, '');
    "google, yahoo"
    

    Breakdown:

    /
      ^( *, *)+     # Match start of string followed by zero or more spaces
                    # followed by , followed by zero or more spaces.
                    # Repeat one or more times
      |             # regex or
      (, *(?=,|$))+ # Match , followed by zero or more spaces which have a comma
                    # after it or EOL. Repeat one or more times
    /g              # `g` modifier will run on until there is no more matches
    

    (?=...) is a look ahead will will not move the position of the match but only verify that a the characters are after the match. In our case we look for , or EOL

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

    You need this:

    s = s.replace(/[,\s]{2,}/,""); //Removes double or more commas / spaces
    s = s.replace(/^,*/,""); //Removes all commas from the beginning
    s = s.replace(/,*$/,""); //Removes all commas from the end
    

    EDIT: Made all the changes - should work now.

    0 讨论(0)
提交回复
热议问题