Javascript replace with $ 1 as var

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!

+4
source share
2 answers

Try something like this:

var arr = {'id':10, 'title':'test-page'};

'/page/{id}/{title}'.replace(/\{([\w\d]+?)\}/g, function(a, b) {
    return arr[b] || '';
});

, String. :

String.prototype.template = function(data) {
    return this.replace(/\{([\w\d]+?)\}/g, function(a, b) {
        return data[b] || '';
    });
};

:

'/page/{id}/{title}'.template(arr);
+4

MDN,

. toLowerCase(). , , toLowerCase() .

( toLowerCase() " " )

function replacer(match, p1, p2, p3/*, ...*/, offset, string){
    return arr[p1];
}
var arr = {'id':10, 'title':'test-page'};
'/page/{id}/{title}'.replace(/\{([\w\d]+?)\}/g, replacer);
0

Source: https://habr.com/ru/post/1530863/


All Articles