-2
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;

Because I want to make a expression like angular.js

Sahan
  • 104
  • 7

1 Answers1

1

Use .replace(regExp, function):

"You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string. Note that the function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global."

The arguments to the function are as follows:

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.

Example:

var x = "Hello World {{ 10 + 5 }} {{ 5 - 4 }} ";

x = x.replace(/\{\{([^}]+)}}/g, function(_, match) {
  return eval(match); // absolutely unsafe!!!!!
});

console.log(x);
Andreas
  • 21,535
  • 7
  • 47
  • 56