gpt4 book ai didi

javascript - Typescript - 替换 url 映射中的字符串

转载 作者:行者123 更新时间:2023-11-30 23:54:59 26 4
gpt4 key购买 nike

我有一张这样的 map :

const urlPaths = {
"Signature": "signature/(signatureId)",
"Rule": "signature/(signatureId)/rule/(ruleId)",
};

然后我的 API 中会出现一些数据,例如:

aId: {
signatureId: "999"
}

aId: {
signatureId: "123",
ruleId: "456"
}

我希望能够使用该映射,返回签名或规则的 url,例如:

“签名/999”“签名/123/rule/456”

我遇到过正则表达式替换,但想知道,在这种情况下我真的可以使用它吗?

function createUrl(url, regex, aId){
url.replace(regex,(id) => aId[id])
}

不确定是否可能/如何处理或者我需要其他东西吗?

任何想法表示赞赏。

谢谢。

最佳答案

不确定 RegExp 是否绝对必要,因为您要替换的模式与您的属性名称相匹配。你可以这样做:

const urlPaths = {
"Signature": "signature/(signatureId)",
"Rule": "signature/(signatureId)/rule/(ruleId)",
};

const aId1 = {
signatureId: "999"
};

const aId2 = {
signatureId: "123",
ruleId: "456"
};

const createUrl = (url, aId) => {
let newUrl = url;
Object.entries(aId).forEach(([key, value]) => {
newUrl = newUrl.replace(`(${key})`, value);
});
return newUrl;
}

console.log(createUrl(urlPaths.Signature, aId1));
console.log(createUrl(urlPaths.Rule, aId2));

如果您确实想使用 RegExp,这里还有一个示例说明它的工作原理

const urlPaths = {
"Signature": "signature/(signatureId)",
"Rule": "signature/(signatureId)/rule/(ruleId)",
};

const aId1 = {
signatureId: "999"
};

const aId2 = {
signatureId: "123",
ruleId: "456"
};

const createUrlRegExp = (url, regexs, aId) => {
let newUrl = url;
const replacer = match => aId[match.slice(1, -1)]; // get rid of parentheses around match
regexs.forEach(regex => {
newUrl = newUrl.replace(regex, replacer)
});
return newUrl;
};

console.log(createUrlRegExp(urlPaths.Signature, [/\(signatureId\)/], aId1));
console.log(createUrlRegExp(urlPaths.Rule, [/\(signatureId\)/, /\(ruleId\)/], aId2));

关于javascript - Typescript - 替换 url 映射中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61112777/

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