在字符串中的空格之前添加字母
我想使用普通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
大厦最近的答案如何加入他们在一起的细节会是这样的
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添加到数组的末尾。最后,我们将原始变量设置为与返回的空间组合在一起的数组。
谢谢贾森Gallavin! – klee
如果有如果你想要连续两个空格? –
为一个或多个空格分割使用x.split(“+”); 注意我有一个空格,然后在那里有一个加号。加号就是所谓的正则表达式。 +表示前面的一个或多个项目,在这种情况下是空格。 –
你的意思是'var x = prompt(..)'? –
而你错过了一个'''' – epascarello
你能否准确解释你的问题是什么?确定字符串中的单词有问题吗?将字符插入到字符串中?打印字符串?请特别注意** –