【问题标题】:cut the string and take its part for the function parameter剪切字符串并将其作为函数参数的一部分
【发布时间】:2019-02-20 06:17:26
【问题描述】:
function replace_tags(input, email) {
    return input
    .replace("{randomip}", random.ip)
    .replace("{email}", email)
    .replace("{date}", random.date)
    .replace("{random_number_4}", random.number(4))
}

我有上面的函数可以把用户输入的字符串变成函数或变量的返回值

我是{random_number_4} 我想打破字符串并取数字4作为函数random.number(4)中的参数

如果用户输入 {random_number_x} 字符串,我希望它会得到random.number(x)

我最有可能使用什么方法来中断和替换字符串?

【问题讨论】:

    标签: javascript node.js string replace split


    【解决方案1】:

    可以使用replace回调函数:

    function replace_tags(input, email) {
        return input
        .replace("{randomip}", random.ip)
        .replace("{email}", email)
        .replace("{date}", random.date)
        .replace(/\{random_number_(\d+)\}/g, (_, n) => random.number(n))
    }
    

    【讨论】:

      【解决方案2】:

      你可以使用regex with a callback:

      var random = {
        number: (x) => Math.floor(Math.random() * x)
      };
      
      function replace_tags(input, email) {
          return input
            .replace("{randomip}", random.ip)
            .replace("{email}", email)
            .replace("{date}", random.date)
            .replace(/{random_number_(\d+)}/g, (_, number) => random.number(number))
      }
      
      console.log(replace_tags('test {email} {random_number_4} {random_number_8}', 'test@example.com'));

      【讨论】:

        猜你喜欢
        • 2016-04-26
        • 2023-02-18
        • 1970-01-01
        • 2011-07-31
        • 1970-01-01
        • 1970-01-01
        • 2015-07-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多