var x = "Hello World {{ 10 + 5 }} {{ 5 - 4 }} ";
x = x.replace( "{{"+/* text */+"}}" , eval( /* text */) );
alert(x); // It's output should be " Hello World 15 1 ";
// How I do this with regEx and eval function;
因为我想制作一个像angular.js
这样的表达式答案 0 :(得分:1)
" 您可以指定一个函数作为第二个参数。在这种情况下,将在执行匹配后调用该函数。函数的结果(返回值)将用作替换字符串。请注意,如果第一个参数中的正则表达式是全局的,则每次完全匹配都会多次调用该函数。"
该函数的参数如下:
Possible name | Supplied value ---------------|-------------------------------------------------------- match | The matched substring. (Corresponds to $& above.) | p1, p2, ... | The nth parenthesized submatch string, provided | the first argument to replace() was a RegExp object. | (Corresponds to $1, $2, etc. above.) For example, | if /(\a+)(\b+)/, was given, p1 is the match for \a+, | and p2 for \b+. | offset | The offset of the matched substring within the whole | string being examined. (For example, if the whole | string was 'abcd', and the matched substring was 'bc', | then this argument will be 1.) | string | The whole string being examined.
示例:
var x = "Hello World {{ 10 + 5 }} {{ 5 - 4 }} ";
x = x.replace(/\{\{([^}]+)}}/g, function(_, match) {
return eval(match); // absolutely unsafe!!!!!
});
console.log(x);