因此,我试图用来自我的matchedResult对象的适当值替换下面的url:
var matchedResult={
"username": "foo",
"token": "123"
}
var oURL = "https://graph.facebook.com/#{username}/posts?access_token=#{token}";我尝试了以下几点:
var matchedResult={
"username": "foo",
"token": "123"
}
var match,
regex = /#\{(.*?)\}/g,
oURL = "https://graph.facebook.com/#{username}/posts?access_token=#{token}";
while (match = regex.exec(oURL)) {
oURL.replace(match[0], matchedResult[match[1]])
}
console.log(oURL);但结果仍然是
"https://graph.facebook.com/#{username}/posts?access_token=#{token}“
而不是
我在这里做错什么了?
发布于 2015-06-26 19:20:21
String.prototype.replace不修改原始字符串,因为JavaScript的字符串是不可变的,而是返回一个新的string对象。引用MDN的话,
replace()方法返回一个新的字符串,其部分或全部匹配的pattern替换为replacement。
因此,您需要将replace的结果分配给oURL,这样旧的替换仍然在oURL中,如下所示
oURL = oURL.replace(match[0], matchedResult[match[1]]);ECMAScript 2015 (ECMAScript 6)实现的方式
如果您所处的环境支持ECMA脚本2015的准字符串文字/模板字符串,那么您可以简单地
`https://graph.facebook.com/${matchedResult.username}/posts?access_token=${matchedResult.token}`注意:末端的回标是新语法的一部分。
发布于 2015-06-26 19:20:35
您需要从
oURL.replace(match[0], matchedResult[match[1]])至
oURL = oURL.replace(match[0], matchedResult[match[1]])https://stackoverflow.com/questions/31080620
复制相似问题