开发者

Variable RegEx String Replacement in JavaScript

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜