javascript - 如何在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);
解决方案
您需要使用 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);
推荐阅读
- c# - 使用 c# 更改默认纸张大小不起作用
- azure - 没有密钥的 JSON 数组 - Azure 逻辑应用
- elasticsearch - 如何在 kubernetes 上创建没有此错误 elasticsearch 的 pod
- npm - 在安装后脚本中运行“下一个构建”后出现“需要适当的加载器”错误
- javascript - 为什么hammer.js 刷卡不适用于iPhone
- python - 我可以在 kubernetes python 客户端中使用正则表达式作为作业名称吗?
- angular - 如何使用 Angular 服务提供第三方 API,如传单或谷歌地图?
- wso2 - 导出 WSO2 API
- ios - Nativescript 是否使用 UIWebView API
- forms - 如何从另一个 dart 文件中调用有状态小部件(有表单)方法?- Flutter