js Howto Declare a String Over Multiple Lines
Share
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));