Home > Article > Web Front-end > JavaScript text template usage examples_javascript skills
The example in this article describes the usage of javascript text template. Share it with everyone for your reference. The details are as follows:
This is a small function I wrote based on the Prism.js algorithm. There is nothing much to say. As a programmer, you should understand it in seconds after looking at the example.
String template engine class:
/*class*/StringTemplate = function ( /* Optional {patt: RegExp, clPatt: RegExp}*/pattern) { if (!!pattern) { this.patt = pattern.patt; this.clPatt = pattern.clPatt; } else { this.patt = /%\{\s*[\w\-]+\s*\}/g; this.clPatt = /(^%\{\s*)|(\s*\}$)/g; } this.format = function(val, map) { var ls = []; var res; var prevEnd = 0; while ((res = this.patt.exec(val)) != null) { var va = res[0]; var start = val.substr(prevEnd, res.index - prevEnd); prevEnd = res.index + va.length; ls.push(start); var vac = va.replace(this.clPatt, ""); ls.push(map[vac]); } ls.push(val.substr(prevEnd, val.length)); return ls.join(""); } }
How to use:
var str = new StringTemplate().format("你好%{userName }, 欢迎再次登陆%{systemName}",{userName: "小明", systemName: "jb51"}); //str="你好小明, 欢迎再次登陆jb51";
I hope this article will be helpful to everyone’s JavaScript programming design.