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
精彩评论