Example of javascript Text Template usage and javascript example
This document describes how to use a javascript Text Template. Share it with you for your reference. The details are as follows:
This is a small function I wrote with reference to the Prism. js algorithm. There is nothing to say. As a programmer, I should understand the example in seconds.
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(""); }}
Usage:
Var str = new StringTemplate (). format ("Hello % {userName}, welcome to log on again % {systemName}", {userName: "James", systemName: "jb51 "}); // str = "Hello James, welcome to jb51 again ";
I hope this article will help you design javascript programs.