user385729
user385729

Reputation: 1984

Regular expressionJavascript

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?

Upvotes: 3

Views: 64

Answers (3)

You can simplify it by using replace callback method instead of exec, so you not need to work with loops, 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)

Upvotes: 0

thefourtheye
thefourtheye

Reputation: 239443

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 a pattern replaced by a replacement.

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

Upvotes: 6

Nikhil Aggarwal
Nikhil Aggarwal

Reputation: 28445

You need to update the code from

oURL.replace(match[0], matchedResult[match[1]])

to

oURL = oURL.replace(match[0], matchedResult[match[1]])

Upvotes: 2

Related Questions