【发布时间】:2020-05-14 21:54:30
【问题描述】:
我有这个函数来创建它发出请求的位置,存储数据。 (存储为 OBJ)
发出第二个请求以获取要调用的新 URL。此 URL 要求我更新 url 以包含存储数据中的值。
正在保存的数据:
{
"location": {
"ip": "78.152.221.20",
"success": true,
"type": "IPv4",
"continent": "Europe",
"continent_code": "EU",
"country": "Ireland",
"country_code": "IE",
"country_flag": "https://cdn.ipwhois.io/flags/ie.svg",
"country_capital": "Dublin",
"country_phone": "+353",
"country_neighbours": "GB",
"region": "County Dublin",
"city": "Swords",
"latitude": "53.4557467",
"longitude": "-6.2197406",
"asn": "AS15502",
"org": "Vodafone Ireland",
"isp": "Vodafone Ireland Limited",
"timezone": "Europe/Dublin",
"timezone_name": "Greenwich Mean Time",
"timezone_dstOffset": "0",
"timezone_gmtOffset": "0",
"timezone_gmt": "GMT 0:00",
"currency": "Euro",
"currency_code": "EUR",
"currency_symbol": "€",
"currency_rates": "0.926884",
"currency_plural": "euros",
"completed_requests": 49
}
}
第二个请求返回这个我需要更新的 URL:
"url": "https://api.sunrise-sunset.org/json?lat={{ location.latitude }}&lng={{ location.longitude }}"
我试图创建一个操作字符串并返回的函数。一旦返回,它将被设置一个字符串模板文字,如下所示:
`https://api.sunrise-sunset.org/json?lat=${OBJ['location']['latitude']&lng=${OBJ['location']['longitude']`
但它不起作用,它只是使用字符串,而不是将先前存储的值作为 OBJ。
这是我的代码,任何建议或指针或任何东西都将不胜感激。
const interpolateURLorMessage = (string) => {
if (CONST.DEBUG) {
console.log('functions.checkURLorMessage: string:', string);
}
if (!string) {
return null;
}
if (string.includes('{{') && string.includes('}}')) {
const myRegexp = /\{{(.*?)\}}/g;
const matches = string.match(myRegexp);
let newURL = `${string}`;
matches.forEach((ele) => {
const match = ele;
let newMatch = ele.replace('.', '\'][\'');
newMatch = newMatch.replace('{{', '${OBJ[\'');
newMatch = newMatch.replace('}}', '\']');
newMatch = newMatch.replace(/\s/g, '');
newURL = newURL.replace(match, newMatch);
});
return newURL;
} else {
// Noting to interpolate
return string;
}
};
【问题讨论】:
-
您不想使用车把之类的东西吗?那将为您完成工作...
-
你可以做
const parsedURL = Handlebars.compile(url)(locationObj); -
请注意,模板文字本质上是 Javascript,是字符串与表达式连接的语法糖,因此您无法在运行时修改它们。那将是自修改代码或类似执行 eval。
标签: javascript json npm ecmascript-6 string-literals