remove unwanted commas in JavaScript

2020-02-08 09:21发布

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

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

If possible ,google,, , yahoo,, , should become google,yahoo.

I've tried the below code as a starting point, but it seems to be not working as desired.

trimCommas = function(s) {
 s = s.replace(/,*$/, "");
 s = s.replace(/^\,*/, "");
 return s;
}

9条回答
做个烂人
2楼-- · 2020-02-08 10:06

My take:

var cleanStr = str.replace(/^[\s,]+/,"")
                  .replace(/[\s,]+$/,"")
                  .replace(/\s*,+\s*(,+\s*)*/g,",")

This one will work with opera, internet explorer, whatever

Actually tested this last one, and it works!

查看更多
爷、活的狠高调
3楼-- · 2020-02-08 10:08

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

 str  = "    aa,   bb,,   cc  , dd,,,";
 newStr = str.match(/[^\s,]+/g).join(",")
 alert("[" + newStr + "]")
查看更多
不美不萌又怎样
4楼-- · 2020-02-08 10:09

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

查看更多
登录 后发表回答