I have the following situation: There is a specific line containing some vars, such as:
var string = '/page/{id}/{title}';
Now I want to be able to replace {id} and {title} with vars from the following array:
var arr = {'id':10, 'title':'test-page'};
I came up with this little regular expression:
string.replace ( /{([a-zA-Z0-9]+)}/g , '$1' );
Which, as expected, just returns this:
/page/id/title
So, I tried this:
string.replace ( /{([a-zA-Z0-9]+)}/g , arr [ '$1' ] );
But it returns
/page/undefined/undefined
Now I understand that something like this is possible with a loop and so on, but it would be nice to have a one line for this. I'm not very used to JS, so I hope there is some function or option that I don’t know about, which helps me with this :).
Yours faithfully!
source
share