Quick way copy paste blocks of text into Javascript.

udaiveer singh
Code Wave
Published in
2 min readJan 24, 2016

In Php you have a text block like so

echo <<< EOT
//less than tests
var wrong:number = 0;
var passed:number = 0;
if(1 < 1+3) {
println("CORRECT: 1 < 4");
} else {
println("Should not print 1 < 4");
elseWrong = elseWrong + 1;
}
EOT;

But in javascript there is no such thing. If I wanted store that program as a string I have to go back make sure all quotes and special characters are escaped correctly, this quickly become a ugly regex problem. Hmmm I wonder if there is a way to get around this?

<span id=”block1"> 
//less than tests
var wrong:number = 0;
var passed:number = 0;
if(1 < 1+3) {
println("CORRECT: 1 < 4");
} else {
println("Should not print 1 < 4");
elseWrong = elseWrong + 1;
}
</span>

Then with some javascript

var str = $(“#block1”).text();// print the string retaining its format 
console.log(str);
/*"
//less than tests
var wrong:number = 0;
var passed:number = 0;

if(1 < 1+3) {
println(\"CORRECT: 1 < 4\");
} else {
println(\"Should not print 1 < 4\");
elseWrong = elseWrong + 1;
}
"
*/
// print the string stringified just for fun
console.log(JSON.stringify(str));
/*
"\" \n//less than tests \nvar wrong:number = 0; \nvar passed:number = 0;\n\nif(1 < 1+3) {\n println(\\"CORRECT: 1 < 4\\");\n} else {\n println(\\"Should not print 1 < 4\\");\n elseWrong = elseWrong + 1;\n}\n\""
*/

This approach is useful if you want to manually copy paste some sample data into your program. Instead of trying to do a million “+” symbols in the text editor just past it into a form or span.

--

--