So I'm trying to replace the following url with appropriate value from my matchedResult object:
var matchedResult={
"username": "foo",
"token": "123"
}
var oURL = "https://graph.facebook.com/#{username}/posts?access_token=#{token}";
I have tried the following:
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);
but still the result is
"https://graph.facebook.com/#{username}/posts?access_token=#{token}"
instead of
https://graph.facebook.com/foo/posts?access_token=123
What am I doing wrong here?
String.prototype.replace doesn't modify the original string, as JavaScript's strings are immutables, but returns a new String object. Quoting MDN,
The
replace()method returns a new string with some or all matches of apatternreplaced by areplacement.
So, you need to assign the result of the replace to oURL, so that the old replacements are still in oURL, like this
oURL = oURL.replace(match[0], matchedResult[match[1]]);
ECMAScript 2015 (ECMAScript 6) way of doing this
If you are in an environment which supports ECMA Script 2015's Quasi String literals/Template Strings, then you can simply do
`https://graph.facebook.com/${matchedResult.username}/posts?access_token=${matchedResult.token}`
Note: The backticks at the ends are part of the new syntax.
Online Demo with Babel
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With