javascript - 将随机字符串插入每个空格实例中

标签 javascript arrays string random

我正在尝试将随机选择的字符串插入到另一个字符串内的每个空格实例中。

var boom = 'hey there buddy roe';
var space = ' ';
var words = ['cool','rad','tubular','woah', 'noice'];
var random_words = words[Math.floor(Math.random()*words.length)];

for(var i=0; i<boom.length; i++) {
  boom.split(' ').join(space + random_words + space);
}

输出为:

=> 'hey woah there woah buddy woah roe'

我从数组中随机选择一个项目,但它对每个空格实例使用相同的单词。我想要每次循环遇到空格时随机生成一个单词。

我想要的是:

=> 'hey cool there noice buddy tubular roe'

感谢您的浏览。

(这是 Boomhauer twitter 机器人的测试版,请原谅变量/字符串😅)

最佳答案

也许您可以使用正则表达式,但是,您没有看到您想要的结果,因为您随机选择一个单词,然后用它替换所有出现的空格。

下面的正则表达式将出现的空格替换为回调返回的动态值。您可以将此回调与 for 循环进行比较,但它会迭代找到的空格,这样您就可以用“唯一”随机单词替换每个出现的位置。

const boom = 'hey there buddy roe';
const words = ['cool', 'rad', 'tubular', 'woah', 'noice'];
const random = () => Math.floor(Math.random() * words.length);

let replace = boom.replace(/ /g, () => ` ${words[random()]} `);

console.log(replace);

关于javascript - 将随机字符串插入每个空格实例中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47984414/

相关文章:

javascript - 通过 ajax 将变量从表单 (POST) 发送到另一个 PHP 脚本 (GET)

Javascript:选中单选按钮

php - 从 JavaScript 表单提交运行 PHP

arrays - Mongodb:对分组后的子文档中的值进行求和,然后查找,然后展开

c# - 使用linq将KeyValuePair List的键获取到int []数组

c# - string.Replace 或 stringBuilder.Replace()

javascript - 如何构建 javascript 字符串,以便 vbScript Split 将其拆分回数组中?

javascript - 使用 node.js 将数据显示到从 mongodb 检索的网页中

python - 从字符串中获取有效的 python 列表(javascript 数组)

c++ - 从 C++ 字符串转换为 unsigned char* 并返回