"\n" in php string variable when stored in javascript variable causes line break -
for example php string variable contain
$code="#include<iostream> using namespace std; void main() { cout<<"hello world \n"; }" and in javascript, when do
var text=<?php echo json_encode($code); ?> console.log(text); then gives output
"#include<iostream> using namespace std; void main(){ cout<<"hello world "; }" taking terminating inverted quotes in next line. should do.
lets go backwards desired output generating output. want console.log show value containing \n:
"foo\nbar" that means string literal in javascript code must like
var text = '"foo\\nfoo"'; json_encode takes care of quotes stuff us, need produce php string literally contains \\n.
there couple of ways depending on way generate string:
// single quotes $code = 'foo\\\nbar'; // double quotes $code = "foo\\\\nbar"; // heredoc (same double quotes) $code = <<<code foo\\\\nbar code; alternatively use addcslashes escape existing \ in string:
$code = addslashes('foo\nbar', '\\'); $code = addslashes("foo\\nbar", "\\");
Comments
Post a Comment