Js code that replaces multiple commas with one comma

  • 2020-03-30 03:15:53
  • OfStack

Sometimes there are many commas, so we can not handle, the following function is to replace multiple commas with a comma, easy to handle later.


<script language="javascript">  
var str="asdfk,asdf34,,,,,,5345,,,,"; 
str=str.replace(new RegExp(',+',"gm"),',');
alert(str); 
</script>


A good code:


function dostr(str){
str=trim(str);
var strarry=unique(str.split(","));
str=strarry.join(",");
str=str.replace(/ . /ig,","); 
str=str.replace(/[^0-9,]*/ig,""); 
str=str.replace(new RegExp(',+',"gm"),',');
if (str.substr(0,1)==',') str=str.substr(1);
var reg=/,$/gi;
str=str.replace(reg,"");
return str;
}

Related articles: