我正在尝试将随机选择的字符串插入到另一个字符串内的每个空格实例中。
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/