gpt4 book ai didi

Javascript 循环替换字符串中的数据

转载 作者:行者123 更新时间:2023-12-02 23:53:50 25 4
gpt4 key购买 nike

我有一小段代码正在尝试进行替换。有两个数据对象。一个是包含 {variable} 的 URL 列表,另一个是这些变量的替换值的对象。

我已经创建了一些代码来尝试让它工作,但我认为可能有一种更有效的方法来处理这个问题。

// Content we will look through and replace variables in
let urls = [
'http://www.example.com/{var1}/{var2}',
'http://www.example.com/{var1}/{var4}',
];

// Data used for the replacement
let variables = [{
variable: 'var1',
value: '123'
},
{
variable: 'var2',
value: '456'
},
{
variable: 'var4',
value: '789'
}]

// Will hold the final URLs
let finalURLs = [];

// Loop over all URLS
for (let index = 0; index < urls.length; ++index) {

// Loop over all variables
for (let d = 0; d < data.length; ++d) {

// Set the replaced URL
let u = urls[index].replace('{' + data[d].variable + '}', data[d].value);
finalURLs.push(u);

}

}

// Desired output
finalURLs = [
'http://www.example.com/123/456',
'http://www.example.com/123/789'
]

我确信我在这方面还很遥远,但正在寻找一些关于该怎么做的指示。

最佳答案

您可以使用一个对象作为替换字符串并替换所有找到的值。

var urls = ['http://www.example.com/{var1}/{var2}', 'http://www.example.com/{var1}/{var4}'],
vars = { var1: '123', var2: '456', var4: '789' },
result = urls.map(s => s.replace(/\{([^}]*?)\}/g, (_, v) => v in vars ? vars[v] : v));

console.log(result);

关于Javascript 循环替换字符串中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55510318/

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