【问题标题】:How to replace elements of a string based on the values of an array?如何根据数组的值替换字符串的元素?
【发布时间】:2021-03-23 22:10:39
【问题描述】:

字符串已经定义如下:

const desc = `This is the password you use to access the $0 application. It is not the password for the $1 card. \n With the password, we can only read your statement. No other operations can be performed.`;

数组已经定义如下:

const params = ['American', 'American Black'];

我想更换:

$0 => American,
$1 => American Black

预期结果:

这是您用于访问美国应用程序的密码。这不是美国黑卡的密码。 \n 使用密码,我们只能阅读您的声明。不能进行其他操作。

【问题讨论】:

  • 对,你的呢?
  • 你能改变模板字符串吗?

标签: javascript arrays string replace


【解决方案1】:

如果你想让它适用于 N 个参数,你可以这样做:

const desc = `This is the password you use to access the $0 application. It is not the password for the $1 card. \n With the password, we can only read your statement. No other operations can be performed. Added $2 value, Added $3 value`;
const params = ['American', 'American Black', 'test1', 'test2'];

const result = params.reduce((acum, val, index) => acum.replace("$"+index, val), desc);

console.log(result);

【讨论】:

  • 非常感谢!我只是在正则表达式中做了一个小改动来替换所有出现的地方。这个"$"+indexnew RegExp(\\$${index}, 'g')
【解决方案2】:

试试这个:

const params = ['American', 'American Black'];

const desc = `This is the password you use to access the ${params[0]} application. It is not the password for the ${params[1]} card.\nWith the password, we can only read your statement. No other operations can be performed.`;

console.log(desc)

在处理信用卡和金钱时要格外小心。将这些数据作为变量存储在用户端代码中是非常危险的,因为任何人都可以很容易地读取它。

【讨论】:

    【解决方案3】:

    如果您无法编辑字符串desc,则可以按如下方式替换 $0 和 $1:

    x = desc.split('$0').join(params[0])
    x = x.split('$1').join(params[1])
    
    return x
    

    【讨论】:

      【解决方案4】:

      如果您不想更改这两个常量,您可以简单地将其替换为:

      var newDesc = desc.replace("$0", params[0]).replace("$1", params[1]);
      

      【讨论】:

        猜你喜欢
        • 2014-05-07
        • 1970-01-01
        • 1970-01-01
        • 2017-05-14
        • 2021-12-05
        • 2022-06-17
        • 2015-05-08
        • 2011-04-13
        • 1970-01-01
        相关资源
        最近更新 更多