1.写法
1.普通表示
字符串可以使用单引号或者双引号。多数JS项目约定使用单引号(')。
可以用单引号包含双引号,也可以用双引号包含单引号。
'ab"c"dd'或者"abc'd'e"
如果想单引号包含单引号,或者双引号包含双引号,需要使用转义符号:
'abc\'de' // abc'de "abc\"de" // abc"de
2. 长字符串
如果想写长字符串,不能直接换行,会报错,有2种常见写法。
var str = "Hello world, I'm Lyra"; // 如果想分行写 // 1)在最后加\ var str = "Hello world,\ I'm Lyra"; // 2) 使用+拼接字符
3. 模版字符串
如果想保留书写格式,使用模版字符串。
var str = `a b`
1.模板编译
用js实现html模板。
将模版字符串转为正式的模板,以下是ejs模板示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ejs模版解析</title>
</head>
<body>
<div ></div>
<script>
var data = {
supplies: ['boom', 'cleaner', 'mop']
}
var template = `
<ul>
<% for(let i=0; i<data.supplies.length;i++) {%>
<li><%=data.supplies[i]%></li>
<%}%>
</ul>
`;
/*
中间形式代码:
echo(<ul>);
for(let i=0; i<data.supplies.length;i++) {
echo(<li>)
echo(data.supplies[i])
echo(</li>)
}
echo(</ul>);
*/
// 写一个编译函数
function compile(template) {
// 使用正则表达式解析模板符号,将其转为上面中间形式代码
regExp = /<%([\s\S]+?)%>/g;
regExpEqul = /<%=(.+?)%>/g; // 先执行这个替换,否则会错乱
var template = template
.replace(regExpEqul, '`); \n echo( $1 ); \n echo(`')
.replace(regExp, '`); $1 \n echo(`')
var template = 'echo(`' + template + '`)';
// 定义html输出函数
var output = "";
function echo(html) {
output += html;
}
// 返回一个可以传入数据的函数
return function parse(data) {
eval(template);
return output;
}
}
const innerHtml = compile(template)(data)
window.root.innerHTML = innerHtml;
</script>
</body>
</html>