Skip to main content

js Howto Declare a String Over Multiple Lines

By Sam Deering

JavaScript

Share:

Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

Someone asked me the other day how to declare a string over multiple lines in jQuery. It’s actually plain JavaScript and can be done by simply adding the escape character backslash “” after each line.

As you can see we simply add the backslash to the end of each line to tell the interpreter it’s part of the same long string.

var textFromChris = "me:  we lunchin?
 Sent at 11:34 AM on Friday
 me:  sure
 Sent at 11:58 AM on Friday
 chris:  T=12.30
 Sent at 12:07 PM on Friday";
var timeRegex = /T=([0-9.]+)/gm;
timeRegex.compile(timeRegex);
console.dir(timeRegex.exec(textFromChris));

Common error message: SyntaxError: unterminated string literal
Compatibility: Testing revealed that it works in all major browsers, including IE 6.

Obviously there are other ways we could achieve the same result. We could simply split the string up like this then it doesn’t matter that they are declared on separate lines.

var textFromChris = "me:  we lunchin?" +
 "Sent at 11:34 AM on Friday" +
 "me:  sure" +
 "Sent at 11:58 AM on Friday" +
 "chris:  T=12.30" +
 "Sent at 12:07 PM on Friday";
var timeRegex = /T=([0-9.]+)/gm;
timeRegex.compile(timeRegex);
console.dir(timeRegex.exec(textFromChris));

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

New books out now!

Learn valuable skills with a practical introduction to Python programming!


Give yourself more options and write higher quality CSS with CSS Optimization Basics.