zoukankan      html  css  js  c++  java
  • 字符串实现变量映射

    方案一:

    字符串变量格式要求: ‘some text {$0}’,{$n}为变量

    扩展数组方法:evaluate

    Array.prototype.evaluate = function(str) {
      this.map(function(item, idx) {
        var reg = new RegExp('{\s*\$' + idx + '\s*}', 'g');
        str = str.replace(reg, item);
      });
      return str;
    }

    使用: arr.evaluate(str)

    测试:

               

    方案二:

    字符串变量格式要求: ‘some text { name}’,{name}为变量

    扩展字符串方法: evaluate 

    String.prototype.evaluate = function(map) {
      var txt = this.toString();
      for (var key in map) {
        if (map.hasOwnProperty(key)) {
          var reg = new RegExp('{\s*' + key + '\s*}', 'g');
          txt = txt.replace(reg, map[key]);
        }
      }
      return txt;
    }

    使用: str.evaluate(map)

    测试:

             

    方案二  --  加强版:

    字符串变量格式要求: ‘some text { name}’,{name}为变量,支持深度属性迭代

    扩展字符串方法: evaluate 

    String.prototype.evaluate = function(map, pKey, ptxt) {
      if (pKey) pKey += '.';
      else pKey = ''
    
      var txt = ptxt ? ptxt : this.toString();
      for (var key in map) {
        if (map.hasOwnProperty(key)) {
          if (typeof map[key] == 'object') {
            txt = this.evaluate(map[key], pKey + key, txt);
          } else {
            var reg = new RegExp('{\s*' + pKey + key + '\s*}', 'g');
    // EL表达式版: new RegExp('\${\s*'+ pKey + '\s*}','g'); txt
    = txt.replace(reg, map[key]); } } }
    if(!ptxt) { // 解析完成后清除没有匹配到的表达式
       var rg = new RegExp('{\s*[a-zA-Z0-9\.]+\s*}','g');
    // EL表达式版: new RegExp('\${\s*[a-zA-Z0-9\.]+\s*','g');
    txt = txt.replace(rg,'');
    }
    return txt; }

  • 相关阅读:
    插入排序的Python代码实现
    数据结构基础--二叉堆、优先队列
    数据结构基础--二叉树
    数据结构基础--数组、链表、栈、队列、哈希表
    转:数据结构与算法系列--十大排序(附动态图解
    快速排序的Python代码实现
    选择排序的Python代码实现
    csv文件的读取写法 from Udacity
    Linux下测试ZLAN 5800
    冒泡排序的Python代码实现
  • 原文地址:https://www.cnblogs.com/xtreme/p/10237448.html
Copyright © 2011-2022 走看看