首页 > 解决方案 > 如何在javascript中的每个单词后添加一个符号

问题描述

所以我的代码目前只在满足条件后将 -boink 或 -bork 放在整个字符串之后,但我想要它,以便在每个单词之后根据它是否满足大于或小于的条件添加术语五个字符。例如“My-boink name-boinkk is-boink Emmanuel-bork”

function myFunctionOne(input1, input2) {

var prompt1 = prompt("Please enter 1, 2, 3, or Exit").toLowerCase();
var prompt2 = input2;

if (prompt1 == 1) {
prompt2 = prompt("Please enter a string");

while (prompt2.length === 0) {
  prompt2 = prompt("You need to enter something");
}

myFunctionOne(prompt1, prompt2);
}

if (prompt1 == 2) {
  if (prompt2.length > 5) {
      console.log(prompt2 + "-bork");
  }
  myFunctionOne(prompt2);
}
else {
  console.log(prompt2 + "-boink")
}

}
 myFunctionOne(1, 2, null);

标签: javascriptstringfunctionloopswhile-loop

解决方案


您需要使用 split 方法将字符串拆分为单词,然后使用 for 循环遍历它们以检查它们是否超过 5 个字符并添加“bork”或“boink”,然后再次加入单词。

我可以为您编写代码,但我认为您自己编写代码会更令人满意。如果你想让我写它想告诉我。

编辑我将编写尽可能接近您已有的代码

function myFunctionOne(input1, input2) {

    var prompt1 = prompt("Please enter 1, 2, 3, or Exit").toLowerCase();
    var prompt2 = input2;

    if (prompt1 == 1) {
        prompt2 = prompt("Please enter a string");

        while (prompt2.length === 0) {
            prompt2 = prompt("You need to enter something");
        }

        myFunctionOne(prompt1, prompt2);
    }

    if (prompt1 == 2) {
        var words = prompt2.split(" "); // we separate the string into words dividing them by space into an array called words
        for(var i = 0; i < words.length; i++){ // we loop from 0 to the length of the array - 1 to access all positions in the array (the last position in arrays are always the length of the array - 1 because they start at 0)  
            if(words[i].length > 5){ //we check if the word in this position of the array is longer than 5 characters
                words[i] += "-bork"; //if it is we add -bork
            }else{
                words[i] += "-boink" //if it is not longer than 5 characters we add -boink
            }
        }
        console.log(words.join(" ")); //we print the array joining the elements with an space to form a string
    }

}
myFunctionOne(1, 2, null);

推荐阅读