I'm trying to generate javascript code snippet and then put it to textarea, so that user could copy ready javascript code.
How to store something like this
"<script type='text/javascript'>
function init_map(){
var myOptions = {
zoom:14,center:new google.maps.LatLng(33.7593664,-118.14817399999998),
mapTypeId: google.maps.MapTypeId.ROADMAP};
}
</script>"
in javascript variable?
3 Answers 3
var abc = "<script type='text/javascript'>\n" +
"function init_map(){\n"+
"var myOptions = {\n"+
"zoom:14,center:new google.maps.LatLng(33.7593664,-118.14817399999998),\n"+
"mapTypeId: google.maps.MapTypeId.ROADMAP};\n"+
"}\n"+
"<\/script>";
alert(abc);
here is the fiddle
1 Comment
You can do it as usual..its just an ASCII string so :
var temp = "<script type='text/javascript'>\n"+
"\tfunction init_map(){\n"+
"\tvar myOptions = {\n"+
"\t\tzoom:14,center:new google.maps.LatLng(33.7593664,-118.14817399999998),\n"+
"\t\tmapTypeId: google.maps.MapTypeId.ROADMAP};\n"+
"\t}\n"+
"<\/script>";
But I would suggest to use the "pre" html tag to display the code. Again everything is a matter of taste and maintainability.
I'm sure that there are way more elegant ways of dealing with code samples display.
You can always use an Open Source JavaScript code beautifier like which can output valid html etc. Have a look on this project : https://github.com/beautify-web/js-beautify
It powers the popular http://jsbeautifier.org/
Comments
You can use the \ character to continue the string on the following line, and also the \n character to create a new line, like this:
var string = "<script type='text/javascript'>\n\
function init_map(){\n\
var myOptions = {\n\
zoom:14,center:new google.maps.LatLng(33.7593664,-118.14817399999998),\n\
mapTypeId: google.maps.MapTypeId.ROADMAP};\n\
}\n\
<\/script>" // the / in </script> needs also to be escaped
document.getElementById('your-text-area-id').value = string;
In your textarea you will see:
screenshot
6 Comments
<\/script> and if you use \n you do not need to use actual newlines<script>document.write('<script>alert("hello")</script>');alert('This will fail');</script></script> will always be interpreted as an end tag for the current <script> tag. It doesn't matter that it's "in a string". See: jsfiddle.net/Z8zhd VS. jsfiddle.net/Z8zhd/1
\nor\r\n, if you want line breaks in your literal, escape them with a single backslash tootext/template, give it anidand usedocument.getElementById('id').textContentto get the string. jsfiddle.net/WfF57/1