开发者

Variable RegEx String Replacement in JavaScript

开发者 https://www.devze.com 2023-02-17 01:36 出处:网络
Is there an easy way to use regular expression to find all matching strings, and then use part of the result as the replacement?

Is there an easy way to use regular expression to find all matching strings, and then use part of the result as the replacement?

For example, consider the following example:

开发者_开发问答
tpl: '<a href="{link_url}">{link_html}</a>';

Here, I would like to run a simple RegEx to look for any match to the '{string}' pattern, and then use what's between the curly braces as an array key. So, the results from the example would be:

array[link_url] and array[link_html]

Thanks!


If I understand you correctly, you want something like this:

var map = {link_url: 'msn.com', link_html: 'MSN' };

var str = '<a href="{link_url}">{link_html}</a>';

str = str.replace(/\{(\w+)\}/g, function(m, p1) {
    return map[p1];
});

which will return

'<a href="msn.com">MSN</a>'

Reference: String.prototoype.replace

0

精彩评论

暂无评论...
验证码 换一张
取 消