JavaScript: String in the source code over more than one line
Question by Chematik | Last update on 2022-03-15 | Created on 2012-04-23
From my programming in PHP, I am used to write strings over two or more lines in the source code, improving the usability and readability significantly. So, when I have a long string and it no longer fits to one line, I hit enter and I land on the next line and everything stays nice and clear.
Now, I have tried the same thing when programming in JavaScript. So, I have written something like this:
alert('This is a long string running over multiple lines');
But that does not seem to work! There is always an error message! What am I doing wrong or how can I write such a long string to my source code correctly?
Related Topics
How to Replace multiple Texts at the same Time
Tutorial | 0 Comments
PHP: Check Strings with Ctype-Functions for Character Classes
Article | 0 Comments
Android Programming: Receive Responce from HTTP POST Request
Tutorial | 0 Comments
Rewrite Text Files with a fixed Line Length
Tutorial | 0 Comments
Show HTML Source Code in Mobile Android Browser
Info | 2 Comments
Repair Text Files with mixed Line Breaks
Tutorial | 0 Comments
CSS: Display Spaces and Paragraphs as in the HTML Code
Tip | 0 Comments
Important Note
Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.
Participate
Ask your own question or write your own article on askingbox.com. That’s how it’s done.
You can do this in JavaScript, by easily connecting long strings with a plus sign. So something like this:
With this, you can definitely get what you want. Why it is not working with the newlines from your example, I do not know. Of course, unfortunately, the plus sign method is much more complicated than this.
Last update on 2022-03-15 | Created on 2012-04-25
In JavaScript, you have to specify a line break in a string with \n. Therefore, "real line breaks" created by pressing the enter key on the keyboard are not possible in strings and that is exactly the thing, you have tried in your example above.
In PHP, this is different. Here you can also press the enter key to create a line break within a string. If the string is outputed using echo, of course, the line break will only be visible in the source code, since in HTML, only <br>, <p> and so on are displayed as a real line break also on the website.
To come back to your example. There are two possibilities:
Either you do it, as proposed by PlasmaTV, with connecting several strings together, or you write a backslash at the end of each line. The first option is preferable, because the second option is possibly not supported by each browser.
Last update on 2022-03-15 | Created on 2012-04-26