Home > Web Front-end > JS Tutorial > JavaScript text template usage examples_javascript skills

JavaScript text template usage examples_javascript skills

WBOY
Release: 2016-05-16 15:48:00
Original
1200 people have browsed it

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("");
  }
}

Copy after login

How to use:

var str = new StringTemplate().format("你好%{userName }, 欢迎再次登陆%{systemName}",{userName: "小明", systemName: "jb51"});
//str="你好小明, 欢迎再次登陆jb51";

Copy after login

I hope this article will be helpful to everyone’s JavaScript programming design.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template