在字符串中的空格之前添加字母

问题描述:

我想使用普通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

你能否准确解释你的问题是什么?确定字符串中的单词有问题吗?将字符插入到字符串中?打印字符串?请特别注意** –

大厦最近的答案如何加入他们在一起的细节会是这样的

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(“+”); 注意我有一个空格,然后在那里有一个加号。加号就是所谓的正则表达式。 +表示前面的一个或多个项目,在这种情况下是空格。 –

你可以使用split,这将在你提供给它的字符的每次出现分裂的字符串,并返回一个数组。因此"Type a sentence here".split(" ")将返回["Type", "a", "sentence", "here"]

然后,您可以迭代该数组并在每个元素的末尾添加一个字符!然后用join将数组转换回字符串。确保你通过加入正确的分隔符!

+0

谢谢你哈哈 – klee