-2

How can I add a new line within JavaScript? I've tried to use \n and \r\n, but nothing happened. This is a portion of the code:

var dbFile = "";
dbFile += "<"+"?"+"php\r\n\r\n<br/>";
dbFile += "class DataBaseConnection {\r\n\r\n";
dbFile += "\tprotected static $db;\r\n";

this is my code PHP for creating a file

function createFiles($folderName, $fileName, $content){
  $ourFileName = $folderName."/".$fileName;
  $ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
  fwrite($ourFileHandle, $content);
  fclose($ourFileHandle); 
}

and I pass the content through ajax

lexalo
  • 23
  • 6
  • 2
    if you want to display a new line in HTML, you use the `
    ` tag.
    – Derek Aug 28 '14 at 14:23
  • http://stackoverflow.com/questions/1155678/javascript-string-newline-character – sadiqmrd Aug 28 '14 at 14:24
  • http://www.sitepoint.com/line-endings-in-javascript/ – Donal Aug 28 '14 at 14:25
  • What exactly do you mean when you say that nothing happens? How do you use the string? What do you expect the newlines to do, and what actually happens? – Guffa Aug 28 '14 at 14:25
  • I want to put dbFile into a file – lexalo Aug 28 '14 at 14:25
  • Replace newlines with `
    ` or place the original text in a `
    ` element or apply the `white-space:pre` style to another containing element.
    – canon Aug 28 '14 at 14:26
  • There is nothing wrong with the line breaks that you have in the code, so if they don't work as exepcted there either is something wrong with the code that uses the string, or possibly your expectation of what the newlines would do. – Guffa Aug 28 '14 at 14:29
  • @Guffa I want to write this code into a php file (create a file which contains dbFile). But it's created in a single line and this is the problem – lexalo Aug 28 '14 at 14:29
  • How are you sending the JavaScript lines to your server, and could you please edit your question to include the relevant PHP code? – Chris Forrence Aug 28 '14 at 14:41

1 Answers1

1

Yep, it does work. I've just tested it in Chrome's Developer console and it's OK.

Another option if you want is:

var lines = [];
lines[0] = "line 1 ";
lines[1] = "line 2 ";
lines[2] = "last line ";

lines.join("\n");

outputs:

"line 1 
line 2 
last line "
nachodd
  • 703
  • 6
  • 7
  • it works, but when I write the lines in a php file by fwrite function, the line breaks don't work – lexalo Aug 28 '14 at 14:35
  • @lexalo , Check this answer. Hope it helps you: [link](http://stackoverflow.com/questions/3066421/writing-a-new-line-to-file-in-php#answer-3066426) – nachodd Aug 28 '14 at 16:25