String expression support,"hello ${name}".evaluate( [optional context] ); - Node.js String

Node.js examples for String:String Value

Description

String expression support,"hello ${name}".evaluate( [optional context] );

Demo Code


/**/*  w  w w  . j  a  v a2 s  .  c  om*/
 * string expression support
 * @param ctx
 *          - the context of the expression (window is the default context)
 * usage: "hello ${name}".evaluate( [optional context] );
 *        - where name is a property of the context
 *
 * @author jaycverg
 */
String.prototype.evaluate = function( ctx ) {

    ctx = ctx? ctx : window;

    var str = this, match;
    while( (match = str.match(/\\?[\$|#]{([^{}]+)}/)) ) {
    if( match[0].length > 3 && match[0][0] == '\\' )
      str = str.replace( match[0], '@@' + match[0].substring(2) );
    else
      str = str.replace( match[0], _evaluate(match[1]) );
    }
  str = str.replace('@@{', '#{');
    return str+''; //return the parsed value

    //-- helper methods
    function _evaluate(str) {
    try {
      var result;
      with( ctx ) {
        result = eval( str );
      }
      if(result == null || result == undefined) result = '';
      return result+'';
    }
    catch(e) {
      if( String.DEBUG_EVAL && window.console ) console.log( 'Error: ' + e.message + ', expr: ' + str );
      return '';
    }
    }
    
    function strEscape( str ) {
    return str.replace(/'/g, '\\\'')
              .replace(/\n/g, '\\n')
              .replace(/\t/, '\\t');
  }
};

Related Tutorials