因此,我尝试使用我的matchResult对象中的适当值替换以下网址:
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}”
代替
我在这里做错了什么?
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 Script 2015的Quasi String文字/模板字符串,则只需执行以下操作
`https://graph.facebook.com/${matchedResult.username}/posts?access_token=${matchedResult.token}`
注意:末尾的反引号是新语法的一部分。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句