33 Votes

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?

ReplyPositiveNegativeDateVotes
11 Vote

You can do this in JavaScript, by easily connecting long strings with a plus sign. So something like this:

alert('This is a long string ' +
'running over ' +
'multiple lines');

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

ReplyPositive Negative
33 Votes

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:

// first possibility
alert('This is a ' +
'long string');
 
// second possibility
alert('This is a \
long string');

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

ReplyPositive Negative
Reply

Related Topics

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.