首页 > 代码库 > js通过replace()方法配合正则去除空格

js通过replace()方法配合正则去除空格

<script>

  //去掉全部空格

  var str = " 546546 4564 46 46 88 88 ";

  var str = str.replace(/\s+/g,"");//生成新的字符串,并未对原字符串修改

  console.log(str);

 

  //去掉左空格

  var str1 = " 546546 4564 46 46 88 88 ";

  var str1 = str1.replace(/^\s*/,"");

  console.log(str1);

 

  //去掉右空格

  var str2 = " 546546 4564 46 46 88 88 ";

  var str2 = str2.replace(/(\s*$)/g,"");

  console.log(str2);

 

  //去掉左右空格

  var str3 = " 546546 4564 46 46 88 88 ";

  var str3 = str3.replace(/^\s+|\s+$/g,"");

  console.log(str3)

</script>

js通过replace()方法配合正则去除空格