我们正在构建的部分工具在很大程度上依赖于正则表达式。 有些事情正在使用标准的javascript'`RegExp。
动态替换具有实际价值的占位符。我们所有的占位符都是这样的:
{{key}}
在大多数情况下,替换是前进和轻松的,我们建立匹配模式:
var pattern = new RegExp('{{key}}', 'g');
但是,至少有一种情况,这种方法不起作用。假设我们有一个a
标记,其中包含占位符< href:
<a href="http://google.com?q={{key}}">http://google.com?q={{key}}</a>
我们需要替换占位符是一个HTML代码(在某些情况下),但是你可以想象,它打破了标记。
注意:它可能是链接中的任何链接或任何内容。
如何只替换不在href
内的占位符?它甚至可能吗?
答案 0 :(得分:0)
根据您对{{key}}
内href
的要求,您可以转义大括号,也可以添加对过滤器的支持。
逃逸:
var values = {"key": "stackoverflow"};
var html = template.replace(/\\([{}\\])|{{(\w+)}}/g, function (match, esc, name) {
// Remove backslashes from an escaped characters, or replace placeholders
// by their values.
return esc ? esc : values[name];
});
示例:
<a href="http://google.com?q=\{{key}}">http://google.com?q={{key}}</a>
过滤器:
var values = {"key": "stackoverflow"};
var filters = {
"quote": function (value) {
return quote.replace(/"/g, """);
}
};
var html = template.replace(/{{(\w+(?:\s*\|\s*\w+)*)}}/g, function (match, expr) {
var names = expr.split(/\s*\|\s*/g);
var value = values[expr[0]];
for (var i = 1; i < names.length; i++) {
value = filters[name[i]](value);
}
});
示例:
<a href="http://google.com?q={{key|quote}}">http://google.com?q={{key}}</a>
您也可以使用AngularJS的内置模板。
var templateElm = angular.element("<div>").html(template);
var innerScope = $scope.$new(true);
// Shallow copy values into the scope
angular.extend(innerScope, values);
var elem = $compile(templateElm)(innerScope);
// Wait for automatic $digest to complete
$timeout(function () {
var html = elem.html();
innerScope.$destroy();
// Do something with 'html'
});