"\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

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -