2011-09-23 115 views
0

我是Javascript新手,需要大學課程上的一些幫助以用字符串「spaces」替換字符串中的所有空格。javascript - 用字符串替換空格

我用下面的代碼,但我不能得到它的工作:

<html> 
<body> 
<script type ="text/javascript"> 
// Program to replace any spaces in a string of text with the word "spaces". 
var str = "Visit Micro soft!"; 

var result = ""; 

For (var index = 0; index < str.length ; index = index + 1) 
{ 
    if (str.charAt(index)= " ") 
    { 
     result = result + "space"; 

    } 
    else 
    { 
     result = result + (str.charAt(index)); 

    } 

} 

document.write(" The answer is " + result); 
</script> 
</body> 
</html> 
+2

你如果語句需要==而不是= =。 ==用於比較,=用於將變量保存在變量中(賦值) –

+2

它以什麼方式「不起作用」? – graphicdivine

回答

1

正如其他人所提到的有在你的代碼的幾個明顯的錯誤:

  1. 控制流關鍵字for必須全部小寫。
  2. 賦值運算符=與比較運算符=====不同。

如果您可以使用庫函數,那麼這個問題看起來很適合JavaScript String.replace(regex,str) function

+0

嘿,現在。這顯然是入門級的入門級任務。如果他抽出正則表達式,老師會有點腥。 :p –

+0

@ImportedNoob:true,但是我敢打賭,如果你在互聯網上搜索「JavaScript字符串替換」(簡單地從作業目標導出),你可以將自己放到同一個地方...... – maerics

0

你應該使用字符串replace方法。不方便,沒有replaceAll,但你可以使用循環替換所有的反正。

替換的實施例:

var word = "Hello" 
word = word.replace('e', 'r') 
alert(word) //word = "Hrllo" 

第二工具,這將是對你有用是indexOf,其中一個串中的串發生,它告訴你。如果字符串沒有出現,它將返回-1。

例子:

var sentence = "StackOverflow is helpful" 
alert(sentence.indexOf(' ')) //alerts 13 
alert(sentence.indexOf('z')) //alerts -1 
1

另一種選擇是完全跳過for週期和使用正則表達式:

"Visit Micro soft!".replace(/(\s)/g, '');