/* ------------------------------
// 字符串模板1,语法严格,不能混用,效率相对较高
// 使用 {{ }} 作为标记是为了允许在模板中使用 JSON 字符串

// 用法 1(对象参数,对象可多次调用):
var say = "对 象:{{hi}}, {{to}}! {{hello}}, {{world}}!"
say = say.format({hi:"Hello", to:"World"})
         .format({hello:"你好", world:"世界"})
console.log(say)

// 用法 2(数组参数):
var say = "数 组:{{0}}, {{1}}! {{0}}!"
say = say.format(["Hello", "World"])
console.log(say)

// 用法 3(字符串参数,最后一个字符串可以重复使用):
var say = "字符串:{{.}}, {{.}}! {{.}}!"
say = say.format("Hello", "World")
console.log(say)

// 用法 4(多次调用,字符串和数组不能共用,字符串必须首先处理):

// 无数组
var say = "{{.}}:3 2 1, {{hi}}, {{to}}! {{hello}}, {{world}}!"
say = say.format("多 次")
         .format({hi: "Hello"})
         .format({to: "World"})
         .format({hello: "你好", world: "世界"})
console.log(say)

// 无字符串
var say = "多 次:{{2}} {{1}} {{0}}, {{hi}}, {{to}}! {{hello}}, {{world}}!"
say = say.format({hi: "Hello"})
         .format({to: "World"})
         .format([1,2,3])
         .format({hello: "你好", world: "世界"})
console.log(say)

// 字符串和数组共用
var say = "{{.}}:{{2}} {{1}} {{0}}, {{hi}}, {{to}}! {{hello}}, {{world}}!"
say = say.format("出问题")
         .format({hi: "Hello"})
         .format({to: "World"})
         .format([1,2,3])
         .format({hello: "你好", world: "世界"})
console.log(say)

// 没有首先处理字符串
var say = "出问题:{{.}}, {{hi}}, {{to}}! {{hello}}, {{world}}!"
say = say.format({hi: "Hello"})
         .format("3 2 1")
         .format({to: "World"})
         .format({hello: "你好", world: "世界"})
console.log(say)
------------------------------ */
String.prototype.format = function(arg) {
	// 安全检查(长度不能小于 {{.}},为后面下标引用做准备)
	var len = this.length
	if (len < 5) { return this }

	var start = 0, result = "", argi = 0

	for (var i=0; i<=len; i++) {
		// 处理 {{ }} 之外的内容
		if (this[i] === "{" && this[i-1] === "{") {
			result += this.slice(start, i-1)
			start = i-1
		} else if (this[i] === "}" && this[i-1] === "}") {
			// 获取 {{ }} 中的索引
			var index = this.slice(start+2, i-1)
			if (index === ".") {          // 字符串
				result += arguments[argi]
				// 最后一个字符串会重复使用
				if (argi < (arguments.length - 1)) {
					argi++
				}
				start = i+1
			} else {                      // 对象或数组
				if (arg[index] != null) {
					result += arg[index]
					start = i+1
				}
			}
		}
	}
	// 处理最后一个 {{ }} 之后的内容
	result += this.slice(start)

	return result
}

/* ------------------------------
// 字符串模板2,语法自由,使用灵活,效率相对较低(基本上模板1就够用了)
// 使用 {{ }} 作为标记是为了允许在模板中使用 JSON 字符串

// 用法 1(对象参数,对象可多次提供):
var say = "对 象:{{hi}}, {{to}}! {{hello}}, {{world}}!"
say = say.template({hi:"Hello", to:"World"}, {hello:"你好"}, {world:"世界"})
console.log(say)

// 用法 2(数组参数):
var say = "数 组:{{0}}, {{1}}! {{0}}!"
say = say.template(["Hello", "World"]);
console.log(say)

// 用法 3(字符串参数,最后一个字符串可以重复使用):
var say = "字符串:{{.}}, {{.}}! {{.}}!"
say = say.template("Hello", "World");
console.log(say)

// 用法 4(混用,对象、数组、字符串可以在参数的任意位置,对象可多次提供):
var say = "{{.}}:{{2}} {{1}} {{0}}, {{hi}}, {{to}}! {{.}}, {{.}}!"
say = say.template([1,2,3], "混 用", {hi: "Hello", to: "World"}, "你好", "世界");
console.log(say)

// 用法 5(多次调用,字符串参数要一次处理完,对象可多次提供):
var say = "{{.}}:{{2}} {{1}} {{0}}, {{hi}}, {{to}}! {{.}}, {{.}}!"
say = say.template([1,2,3])
         .template({hi: "Hello"})
         .template("多 次", "你好", "世界")
         .template({to: "World"});
console.log(say)
------------------------------ */
String.prototype.template = function() {
	// 安全检查(长度不能小于 {{.}},为后面下标引用做准备)
	var len = this.length
	if (len < 5) { return this }

	var start = 0, result = ""
	var objs = [], strs = [], stri = 0

	// 参数分类
	for (var i in arguments) {
		switch (typeof arguments[i]) {
			case "object": objs.push(arguments[i]);break // 对象(包括数组,可以有多个)
			default      : strs.push(arguments[i])       // 其它(当做字符串处理)
		}
	}

	for (var i=0; i<len; i++) {
		// 处理 {{ }} 之外的内容
		if (this[i] === "{" && this[i-1] === "{") {
			result += this.slice(start, i-1)
			start = i-1
		} else if (this[i] === "}" && this[i-1] === "}") {
			// 获取 {{ }} 中的索引
			var index = this.slice(start+2, i-1)
			if (index === "." && strs.length > 0) { // 字符串
				result += strs[stri]
				// 最后一个字符串会重复使用
				if (stri < strs.length - 1) {
					stri++
				}
				start = i+1
			} else {                                // 对象或数组
				for (var obji in objs) {
					if (objs[obji][index] != null) {
						result += objs[obji][index]
						start = i+1
						continue
					}
				}
			}
		}
	}
	// 处理最后一个 {{ }} 之后的内容
	result += this.slice(start)

	return result
}

代码片段 - JavaScript 字符串模板的更多相关文章

  1. JavaScript——字符串——模板字符串

    JavaScript--字符串--模板字符串 字符串可以用反引号包裹起来,其中的${expression}表示特殊的含义,JavaScript会将expression代表的变量的值和反引号中的其它普通 ...

  2. vs _ 用户代码片段 _ html模板

    自定义模板:首选项 -> 用户代码片段 - >(如果没有自己创个)html.json t : 表示缩进 n:表示换行 ----------------------------------- ...

  3. 项目中解决实际问题的代码片段-javascript方法,Vue方法(长期更新)

    总结项目用到的一些处理方法,用来解决数据处理的一些实际问题,所有方法都可以放在一个公共工具方法里面,实现不限ES5,ES6还有些Vue处理的方法. 都是项目中来的,有代码跟图片展示,长期更新. 1.获 ...

  4. HTML代码转换为JavaScript字符串

    我有时在工作中用到字符串拼接基本上来自于此,链接 http://www.css88.com/tool/html2js/

  5. [欣赏代码片段] (JavaScript) 你使用过getComputedStyle没有

    (function() { // IE8 ployfill for GetComputed Style (for Responsive Script below) if (!window.getCom ...

  6. [欣赏代码片段] (JavaScript) Responsive jQuery

    jQuery(document).ready(function($) { /* getting viewport width*/ var responsive_viewport = $(window) ...

  7. vscode 用户代码片段 vue初始化模板 Snippet #新加入开头注释 自动生成文件名 开发日期时间等内容

    vue文件模板 模板变量 https://code.visualstudio.com/docs/editor/userdefinedsnippets#_variables vue.json { // ...

  8. [代码片段]javascript检查图片大小和格式

    function checkImgType(input) { var this_ = document.getElementsByName('imgFile')[0]; var filepath = ...

  9. 代码片段 - JavaScript 求时间差

    // 求时间差1(时间差不能超过一天) function timeDifference1(startTime, endTime) { let times = endTime.getTime() - s ...

随机推荐

  1. 实体框架 (EF) 入门 => 三、CodeFirst 支持的完整特性列表

    KeyAttribute 设置主键.如果为int类型,将自动设置为自增长列. 系统默认以Id或类名+Id作为主键.StringLengthAttribute 可设置最大最小长度以及验证提示信息等.最大 ...

  2. 第三百四十三天 how can I 坚持

    今天又莫名其妙的烦起来了,好没劲. 现在还在看电视机<太阳的后裔>,晚上也没怎么吃饭,干吃了两个馒头,老干妈+生洋葱,好凄惨. 上班看了好长时间会,乱七八糟的. 坚决不跳槽,但得坚持自己的 ...

  3. 第三百二十七天 how can I 坚持

    都没心情学习了,睡觉.太失败了.  好了,你赢了,最怕女人不说话了,我妈一生气就不说话,有点怕我妈,你想删就把我删了吧,我不怪你. 给你个善意的建议,任何事情都要有度,过犹而不及,你是属于那种比较听家 ...

  4. cocos2d-x 知识小结(1)zorder和tag

    <span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255) ...

  5. JS中如何判断null、undefined与NaN

    1.判断undefined: <span style="font-size: small;">var tmp = undefined; if (typeof(tmp)  ...

  6. [转][IIS]发布网站,提示用户 'IIS APPPOOL\***' 登录失败。

    链接:http://www.cnblogs.com/tianguook/p/3881075.html 用户 'IIS APPPOOL\DefaultAppPool' 登录失败. 我在windows8中 ...

  7. Combox和DropDownList控件的区别

    共同点:都是下拉框控件 不同点:Combox用在winform上,DropDownList用在网页上,且两者绑定方式略有不同 绑定数据例子如下—— 1.Combox绑定 DataTable dtBus ...

  8. JavaScript谁动了你的代码

    到目前为止,同学你知道了JavaScript的历史,也了解其"你想是啥就是啥"的变量系统.相信凭借你深厚的Java或者C++功底,再加上程序员特有的自傲气质,你肯定会信心满满:自信 ...

  9. cvc-complex-type.2.4.a: Invalid content was found starting with element

    在写xml的时候又一次总是报cvc-complex-type.2.4.a: Invalid content was found starting with element 错误,还出现小红叉,在网上找 ...

  10. 【M14】明智运用异常规范

    1.异常规范的使用场景是,承诺方法只抛出什么样的异常,或者不抛出异常.如果运行的时候,不满足承诺,C++自动调用unexpected方法,unexpected调用terminate方法,termina ...