Home  >  Article  >  Web Front-end  >  How to embed a large number of string constants in JavaScript_javascript skills

How to embed a large number of string constants in JavaScript_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:29:561085browse

A small number is fine, but if there are many, it will be a dense mass of text. Young artistic people who pay attention to aesthetics will use a large number of characters to connect symbols and even add indents to force it to be replaced by several lines. For example:

Copy code The code is as follows:

var html =
'
This is okay. If there are a lot of double quotes and single quotes in the string, it will be more troublesome. The various escape characters will be dazzling.

Actually there is a little trick that can solve this problem. Everyone always thinks that the string must be inside "..." or '...', which is correct. But there is another place where strings can also be preserved as non-code semantics, and that is a function's toString, which outputs the entire function code as a string - of course the comment part is also retained!
So we write an empty function, which contains only one /**/ comment, which is the constant content we want. Adding a regular expression after toString can extract what we want!

Try it now:

Copy code

{
std::cout << "Hello world" << std::endl;
return 0;
}

*/});


var RES_POEM = _TEXT(function(){/*
> More stars are falling like rain.
BMW carvings are full of fragrance.
The phoenix flute is sounding, the jade pot is spinning, and the fish are all night The dragon dances.
The moth is covered with golden threads of snow and willow.

The crowd is looking for him thousands of times.

Suddenly, when I look back, the man is there in the dim light. );

var res_xml = _Text (function () {/*
& lt; projectDescript & gt;
& lt; name & lt;/name & gt; & gt; & lt;/comment & gt;
& lt; projects>
;/name>
                                                                   ;
                                                          .flexbuilder.project.apollobuilder                                                                 ;


function _TEXT(wrap) {
return wrap.toString().match(//*s([sS]*)s*//)[1];
}
alert(RES_CODE );
alert(RES_POEM);
alert(RES_XML);



OK! In Chrome, the tab in front of each line of comments is removed. If you just put the code, it will not be a big problem~ Of course, the prerequisite is that */
cannot appear in the characters.
It is worth noting that comments will be filtered when compressing the code, and some parts need to be manually excluded.