js字符串中的空格用&nbsp替换的几种方式

  • Post author:
  • Post category:其他


想达到这样的效果,解决调用接口数据传来的多空格字符正确渲染在浏览器页面上,进而方便传值的问题(其实一般情况下,渲染值和实际值视觉效果有所不同)

  • 例如:把str=“a b c” =>“a  b   c”


  • 用原生方法,通过for循环替换字符串的空格

var str="a  b   c"
var strArr=str.split("")//["b","","","b","","","","c"]
for(var i=0;i<strArr.length;i++){
	if(!strArr[i].trim()){
		strArr[i]="&nbsp;"
	}
}
//strArr=>["b","&nbsp;","&nbsp;","b","&nbsp;","&nbsp;","&nbsp;","c"]
str=strArr.join("")//"a&nbsp;&nbsp;b&nbsp;&nbsp;&nbsp;c"


  • 利用正则表达式结合replace替换

var str="a  b   c"
str=str.replace(new RegExp(/( )/g),"&nbsp;")//"a&nbsp;&nbsp;b&nbsp;&nbsp;&nbsp;c"
//或者(注意括号里面是有一个空格的)
str=str.replace(/( )/g,"&nbsp;")//"a&nbsp;&nbsp;b&nbsp;&nbsp;&nbsp;c"



版权声明:本文为weixin_47389477原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。