zoukankan      html  css  js  c++  java
  • 字符串连接类(Javascript)

    转载自: http://www.cnblogs.com/sohighthesky/archive/2011/03/28/string_buf.html

        用字符串连接的类,把以前的方法写成了类的方式,方便调用 ,

    支持实例调用 和静态调用

    参数可以是单独的字符串,或者json的格式,或者类似参数数组的方式,见下面示例 

     /*

     * @author: uedsky
     * @version: 1.0
     */

    /**
     * @class String concat
     * @return {StrBuf/String}
     * @constructor
     
    */
    var StrBuf = function(s) {
        
    this.data = [];
        
    if(s) {
            
    var args = arguments, buf;
            
    if(this instanceof StrBuf){
                
    this.push.apply(this, args);
            }
    else{// static invoke
                buf = new StrBuf();
                buf.push.apply(buf, args);
                
    return buf.toString();
            }
        }
    };
    StrBuf.prototype 
    = {
        
    // add String to the instance
        push: function(s, j){
            
    var args = arguments;
            
    if(args.length < 2) {
                
    this.data.push(s || "");
            }
    else if(typeof j == 'object'){
                
    this.data.push(s.replace(/\$\{([\w.]+)}/g, function($, $1){
                    
    return ($1 in j) ? j[$1] : $;
                }));
            }
    else {
                
    this.data.push(s.replace(/\{(\d+)}/g, function($, $1){
                    
    return args[+$1 + 1];
                }));
            }
        },
        toString: 
    function(){
            
    return this.data.join("");
        }
    };
     
    调用 示例如下:

          var buf = new StrBuf("contructor str\n");

        buf.push("hello,");
        buf.push(
    "Today is {0}, {1}""Monday""March 28th");

        buf.push(
    "${name} is a good ${category} company", {name: "Google", category: "Intenet"});
        document.write(buf);
    // auto call toString method
        console.log(buf);
        console.log(StrBuf(
    "static {0} method""invoke"));

  • 相关阅读:
    Pwn-level3
    【mysql】 mysql忘记密码
    【Linux】linux磁盘管理
    【Linux】Linux系统LVM管理及Raid
    【Git】git撤销与回滚
    【linux】Linux系统SELinux简介
    【Linux】Linux中的网络命令
    【Linux】linux中文本操作利器grep,awk,sed
    【Linux】linux正则表达式及通配符
    【Mysql】mysql数据备份
  • 原文地址:https://www.cnblogs.com/colder/p/1997569.html
Copyright © 2011-2022 走看看