2013-04-25 93 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