2013-04-25 92 views
-1
<!DOCTYPE html> 
<html> 
<body> 

<p id="demo">Click the button to locate where in the string a specifed value occurs.</p> 

<button onclick="myFunction()">Try it</button> 

<script> 
function myFunction() 
{ 
var a =" picture"; 
a.replace(" ",""); 


var n=a.indexOf(" "); 
document.getElementById("demo").innerHTML= n+a+n; 
} 
</script> 

</body> 
</html> 

我想更换“从本例中的‘图片’”(空格)上面替换为“”(空格)不起作用

但结果似乎它没有被替换替换命令。

结果应该是“-1picture-1”替换后但它的“0 picture0”

在图像前面的空间。 (我用.indexOf(”“),以表明

有一个空间在变或不为-1意味着它不)

它是什么?发生请指教

回答

8

replace不修改字符串到位,它返回修改后的字符串。

a = a.replace(" ",""); 
+2

仅供参考使用'.replace(/ /克, '')'如果有超过1个空格在您的字符串,你要全部换掉。 – 2013-04-25 14:40:17

0

您需要返回的值分配回a

var a =" picture"; 
a = a.replace(" ",""); 

编辑:

还要把它扔出去那里有一个.replace(" ","")只会窝rk是空间的第一个实例,它甚至可能不在字符串的开头。如果你是想修剪领先尾随空格,可以这样考虑:

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

我认为这可能工作得很好......

return str.replace(/\s+/g, ''); 

为什么我得到一个downvote? ?

alert("some #$%%&& person gave me a downvote!!".replace(/\s+/g, '')); 

这完全适用!!!!!!

http://jsfiddle.net/ncubica/FBxy2/

+1

Person ncubica = new Person();如果(downVote(ncubica)){ncubica.rage(); } – CrazedCoder 2016-01-15 00:17:15