首页 > javascript怎么过滤下面的这个字符串??

javascript怎么过滤下面的这个字符串??

原字符串:
var str="ul {width: 200px; height:300px;}";
过滤后的字符串:
var str='ul{width:200px;height:300px}';

怎么通过正则 过滤??

我想到的一种方式是:
  str.replace(/(\w*) |(:) |(;) /,"$1");
可得到的结果却成了这样:
var str='ul{width200px;height300px;}';

:分号被吃掉了....
怎么才能实现这样的过滤??



    
     

换个思路,先过滤掉所有的空格,然后再过滤掉}之前的;

str.replace(/\s+/g,"").replace(/;}$/,"}")

要一步到位的话,这样str.replace(/(\s+)|(;(?=}$))/g,"")


看楼上评论,这个应该能满足题主要求str.replace(/(\s+(?={))|\B(\s+)|(;(?=}$))/g,"")
答案来自评论区大神ggsoul


你是要过滤掉字符串中所有的空格和最后的一个分号吗,可以通过下面的方法

var str="ul {width: 200px; height:300px;}";
str = str.replace(/ /g,'');   
str = str.replace(';}','}');

用不到正则吧,通过空格分割成数组,然后再组合起来


<script type="text/javascript">
var str="ul {width: 200px; height:300px;}";
var patt1=/\s/g;
document.write(str.replace(patt1,''));
</script>
【热门文章】
【热门文章】