Home >Web Front-end >JS Tutorial >How to splice a large number of strings in Javascript_javascript skills

How to splice a large number of strings in Javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:15:341314browse

There are heredoc string definition methods in php and python:

php:

Copy code The code is as follows:

$sql=<< select *
from pages
where pagename='$pn'
EOD;

python:
Copy code The code is as follows:

print """
This is an example of a string in the heredoc syntax.
This text can span multiple lines
"""

It is relatively cumbersome to splice a large number of strings in js without a heredoc-style operator:

Splicing method one:

Copy code The code is as follows:

var str = "
Here is line one
And line two
Finally, line three!
";

alert(str);


Splicing method two:
Copy code The code is as follows:

var __template =
''
'#salarySN#'
'#name#'
'#TDR_NAME#'
'#TSD_NAME#'
'#WORK_STATUS#'
'#isleader_display#'
''
'Set role'
'';

JS strings need to break the original string style and be processed per line, which is a bit unbearable.

Give me a solution:

Copy code The code is as follows:

function aHereDoc() {/*
Hello, World!
I am a JavaScript here document.
Use the 'hereDoc' function to extract me.
*/}

function hereDoc(func) {
return func.toString().split(/n/).slice(1, -1).join('n');
}
console.log(hereDoc(aHereDoc));


Use func.toString() to obtain the strings that need to be processed in batches, use split(/n/).slice(1, -1) to remove the first and last two lines of function definition code, and reassemble them.
Statement:
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