3

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?

3 Answers 3

6

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

Sign up to request clarification or add additional context in comments.

2 Comments

Nice answer! Sorry Im new to EC6; do you know whether we can use it in Node.js? How can I use it? Should I require/include something to use their features/syntax? Thanks
As of now, node.js doesn't support it but io.js does.
2

You need to update the code from

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

to

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

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.