【问题标题】:Replace part of string with a letter?用字母替换部分字符串?
【发布时间】:2020-11-21 22:55:41
【问题描述】:

我是 Discord 机器人编程新手,但我很快就学会了。 我的问题如下:

我创建了一个函数,将随机选择的单词中的所有字符替换为 * 现在我检查给定的字母是否是转换后单词的一部分,并返回它出现的次数。

现在是我挣扎的地方!我想显示 *,但我也想将单词中的字母转换回匹配。

有点像这样:

let word = 'emoticon';
let string = convert(word); // returns * * * * * * * *
if (checkChar(letter, word) > 0 ) {
  message.channel.send(`${letter} is found XX number of time(s)`);
  // Code to convert the word back to * * o * * * o * if o was the given letter
  message.channel.send(`${newword} here is a clue!`);
}
else {
  message.channel.send(`${letter} is not found!`);
}

如果有人可以帮助我实现这一目标,我将永远感激不尽!

【问题讨论】:

    标签: node.js bots discord.js


    【解决方案1】:

    您可以使用 replace 方法并向其传递回调以进行更复杂的检查。在这里,我记住要检查的原始单词,然后在我按索引移动隐藏单词时,检查它的字母。

    const original = 'some word'
    let hidden = original.replace(/./g, '*')
    console.log(hidden) // *********
    
    let testLetter = 'o'
    hidden = hidden.replace(/./g, (c, i) => original[i] === testLetter ? testLetter : c)
    console.log(hidden) // "*o****o**"

    【讨论】:

    • 非常感谢!!!我重写了我的代码,现在离终点线又近了一步:D
    猜你喜欢
    • 2016-06-05
    • 2021-03-25
    • 2012-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-19
    • 1970-01-01
    相关资源
    最近更新 更多