Regular ExpressionJavascript
So, I'm trying to replace the following url with the corresponding value from my matchedResult object:
var matchedResult={
"username": "foo",
"token": "123"
}
var oURL = "https://graph.facebook.com/#{username}/posts?access_token=#{token}";
I've 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 the result
" https://graph.facebook.com/# {username} / posts? access_token = # {token}"
instead
What am I doing wrong here?
source to share
String.prototype.replace
does not change the original string as JavaScript strings are immutable, but returns a new String object. Quoting MDN,
The method returns a new string with some or all of the matches replaced with .
replace()
pattern
replacement
So, you need to assign the result replace
to oURL
, so the old replacements are still in oURL
, like this
oURL = oURL.replace(match[0], matchedResult[match[1]]);
ECMAScript 2015 (ECMAScript 6) way to do it
If you are in an environment that supports ECMA Script 2015 Quasi String Literals / String Patterns you can simply do
`https://graph.facebook.com/${matchedResult.username}/posts?access_token=${matchedResult.token}`
Note. Backreferences at the ends are part of the new syntax.
source to share
You can simplify it by using the substitute callback method instead , so you do not need to work with loops : exec
Demo
var matchedResult = {
"username": "foo",
"token": "123"
};
var oURL = "https://graph.facebook.com/#{username}/posts?access_token=#{token}";
oURL = oURL.replace(/#\{([^}]+)\}/g, function(a,b){
return matchedResult[b] || a
});
alert(oURL)
source to share