JS字符串格式化~歡迎來摟~~


/*
    函數:格式化字符串
    參數:str:字符串模板; data:數據
    調用方式:formatString("api/values/{id}/{name}",{id:101,name:"test"});
             formatString("api/values/{0}/{1}",101,"test");
  ****字符串中需要替換的數據用 {} 括起來,注意花括號里面不能有空格,data建議使用自定義對象,也就是python中的字典
*/ function formatString(str, data) { if (!str || data == undefined) { return str; } if (typeof data === "object") { for (var key in data) { if (data.hasOwnProperty(key)) { str = str.replace(new RegExp("\{" + key + "\}", "g"), data[key]); } } } else { var args = arguments, reg = new RegExp("\{([0-" + (args.length - 1) + "])\}", "g"); return str.replace(reg, function(match, index) { return args[index - (-1)]; }); } return str; }

例子來了~

text_str = "<tr>
            <th>{id}</th>
            <th>{name}</th>
             <th>{author}</th>
             <th>{publish}</th>
            </tr>"
 data = {"id":1,"name":"金瓶","author":"小強","publish":"西北出版社"};         
new_str = formatString(str, data)

## new_str ===> "<tr>
            <th>1</th>
            <th>'金瓶'</th>
            <th>"小強"</th>
             <th>"西北出版社"</th>
            </tr>"

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM