2015-09-16 169 views
0

我想使用普通javascript在每個單詞的末尾添加一個字母(任意字母,讓說p),但我不知道如何做到這一點。 我已經有這個不完整的代碼。在字符串中的空格之前添加字母

var y = prompt("type a sentence here!"); //person types in sentence that will get changed// 
function funkyfunction() { 
    for(var i=0;i<x.length;i++){ 
     if(x.charAt(i)==" "){ 

     } 
    } 
}; 
funkyfunction(); //would call the function and print the result 
+0

你的意思是'var x = prompt(..)'? –

+1

而你錯過了一個'''' – epascarello

+1

你能否準確解釋你的問題是什麼?確定字符串中的單詞有問題嗎?將字符插入到字符串中?打印字符串?請特別注意** –

回答

0

大廈最近的答案如何加入他們在一起的細節會是這樣的

var x = prompt("type a sentence here!"); //person types in sentence that will get changed// 
function funkyfunction() 
{ 
    var words = x.split(" "); 
    for (var i = 0; i < words.length; i++) { 

     words[i] += "p"; 
    } 
    x = words.join(" "); 
    console.log(x); // or alert(x); which ever is most useful 
} 
funkyfunction(); //would call the function and print the result 

正如你可以看到,我們分割字符串成的空間分隔符的陣列來獲得數組單詞,然後我們遍歷數組中的項目,並將p添加到數組的末尾。最後,我們將原始變量設置爲與返回的空間組合在一起的數組。

+0

謝謝賈森Gallavin! – klee

+0

如果有如果你想要連續兩個空格? –

+0

爲一個或多個空格分割使用x.split(「+」); 注意我有一個空格,然後在那裏有一個加號。加號就是所謂的正則表達式。 +表示前面的一個或多個項目,在這種情況下是空格。 –

1

你可以使用split,這將在你提供給它的字符的每次出現分裂的字符串,並返回一個數組。因此"Type a sentence here".split(" ")將返回["Type", "a", "sentence", "here"]

然後,您可以迭代該數組並在每個元素的末尾添加一個字符!然後用join將數組轉換回字符串。確保你通過加入正確的分隔符!

+0

謝謝你哈哈 – klee

相關問題