gpt4 book ai didi

Javascript 用模式替换参数

转载 作者:行者123 更新时间:2023-11-30 08:44:26 25 4
gpt4 key购买 nike

我只想根据模式替换字符串中的所有参数:

例如:

var myString = "Hello Mr.{param1}, today is {param2} and hope ...";

我不知道我们如何找到 {#} 模式并替换为 JavaScript 中的值。

最佳答案

function replace(str, params) {
for(var i in params)
if(params.hasOwnProperty(i))
str = str.replace('{'+i+'}', params[i]);
return str;
}
replace("Hello Mr.{param1}, today is {param2} and hope ...", {
param1: 'foo',
param2: 'bar'
}); // "Hello Mr.foo, today is bar and hope ..."

请注意,只会替换每个参数的第一次出现。


如果你想替换所有出现的地方,在replace中使用

str = str.replace(
new RegExp(
('{'+i+'}').replace(/[.^$*+?()[{\|]/g, '\\$&'),
'g'
),
params[i]
);

关于Javascript 用模式替换参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23177126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com