Many times we want to create very long strings, such as when adding HTML dynamically. In PHP we can use
- nowdoc (single quote) delimiter string: does not recognize variables, does not recognize escape characters (except \' and \\, which represent single quotes and backslashes, respectively)
- heredoc (double quote) delimiter string: identify variables, identify escape characters
to create multiline strings. But how to do it in JS?
One: connect directly with the plus sign
var ts = '<!DOCTYPE html>'+
'<html lang="en">'+
'<head>'+
' <meta charset="UTF-8">'+
' <title>Document</title>'+
'</head>'+
'<body>'+
' hello world'+
'</body>'+
'</html>'
Second, use the backslash (continuation character)
var ts = '<!DOCTYPE html>\
<html lang="en">\
<head>\
<meta charset="UTF-8">\
<title>Document</title>\
</head>\
<body>\
hello world\
</body>\
</html>'
3. String array join
var ts = ['<!DOCTYPE html>',
'<html lang="en">',
'<head>',
' <meta charset="UTF-8">',
' <title>Document</title>',
'</head>',
'<body>',
' hello world',
'</body>',
'</html>'].join('\n')
四、String.prototype.concat
var ts = String.prototype.concat.call('<!DOCTYPE html>',
'<html lang="en">',
'<head>',
' <meta charset="UTF-8">',
' <title>Document</title>',
'</head>',
'<body>',
' hello world',
'</body>',
'</html>')
五、Function.prototype.toString()
==Note: This method ensures that JS is not compressed to remove comments, and pay attention not to remove the text when removing the comment number. ==
var ts = (function(){/*
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
hello world
</body>
</html>
*/}).toString().split('\n').slice(1,-1).join('\n') + '\n'
Can be encapsulated as a method:
function doc(fn) {
return fn.toString().split('\n').slice(1,-1).join('\n') + '\n'
}
var ts = doc(function(){/*
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
hello world
</body>
</html>
*/})
六、CoffeeScript
To compile to get the JS file
ts = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
hello world
</body>
</html>
"""
Seven, template strings (ES6 new features)
== is not supported by IE! ! ! is backticks "`" instead of single quotes "'" ==
template strings - JavaScript | MDN
var ts = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
hello world
</body>
</html>`