替换多个空格

时间:2012-11-27 08:12:01

标签: javascript jquery

var firefoxIngs = myText.replace(/ /g," ");

这是我的字符串:

"h  a"//it has two empty spaces between h and a

代码之后变为:

"h a"//it has one empty spaces between h and a

我希望它是

"h  a"

为什么会发生这种情况以及如何解决?

2 个答案:

答案 0 :(得分:3)

按预期工作

console.log("h  a".replace(/ /g," "));

在字符串上,您可能缺少一个空格。

结果:

h  a

参考 LIVE DEMO

答案 1 :(得分:0)

这也有效

<script type="text/javascript">
 function validate(){
  str=document.getElementById("input").value;

str= str.replace(/\s/g, '  ');
console.log(str);
}
</script>
    <input id="input" type="text"/>
<input type="button" onclick="validate()" />