方法如下:
- 1. str.replace(/oldString/g,newString)
- 2. str.replace(new RegExp(oldString,"gm"),newString)
- 3. String 对象原型方法 replaceAll
示例代码:
// 字符替换方法实现 String.prototype.replaceAll = function(s1,s2){ return this.replace(new RegExp(s1,"gm"),s2); }
/** * 设置事件选项 * * @param template */ EventTemplate.prototype.setEventTemplates = function () { var that = this; that.eventListDiv.html(""); var templates = that.getEventTemplates(); for (var key in templates) { var template = templates[key]; var key = template["KEY"]; var name = template["NAME"]; if(undefined == name || "" == name.trim()){ continue; } var icon = template["ICON"]; var templateHtml = '<div class="item">\n' + ' <input type="checkbox" name="sj-type" id="EVENT-#{eventKey}" value="#{eventKey}" >\n' + ' <label for="EVENT-#{eventKey}">#{name}</label>\n' + ' <img src="upload/event/' + icon + '">\n' + ' </div>'; templateHtml = templateHtml.replaceAll("#{eventKey}",key); templateHtml = templateHtml.replaceAll("#{name}",name); that.eventListDiv.append(templateHtml); // 绑定点击事件 $('#eventListDiv input:checkbox[id="EVENT-'+key+'"]').off("click").on('click',function(){ window.Event.recheckEvents(); }); } }
注意:替换字符表达式不能是${xxxxx}这种格式。
纸上得来终觉浅,绝知此事要躬行。