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

https://graph.facebook.com/foo/posts?access_token=123

What am I doing wrong here?

+3


source to share


3 answers


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.

Online demo with Babel

+6


source


You need to update your code from

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

      



to

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

      

+2


source


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)
      

Run codeHide result


0


source







All Articles