Ryan Sampson
Ryan Sampson

Reputation: 6817

Using '\' in javascript to declare string occupying multiple lines

While looking through a 3rd party JavaScript API and example code I noticed the following declaration. Basically XML assigned to a string but they seem to split it up on multiple lines using '\', I was unaware this could be done in javascript. Could anyone provide some more details on how this works?

Thanks.

var PrimaryChannel = '<ChannelParams ChannelType="Digital"> \
                                <DigitalChannelParams \
                                    PhysicalChannelIDType="Cable" \
                                    PhysicalChannelID="107" \
                                    DemodMode="QAM256" \
                                    ProgramSelectionMode="PATProgram" \
                                    ProgramID="2"> \
                                </DigitalChannelParams> \
                            </ChannelParams>';

Upvotes: 2

Views: 2103

Answers (3)

Sam Saint-Pettersen
Sam Saint-Pettersen

Reputation: 511

Yes, you can do that. \ is the line continuation character in JavaScript.

Edit: It's technically an escape character.

Upvotes: 1

CaffGeek
CaffGeek

Reputation: 22064

It is escaping the newline character, but it's not recommended. If you minify your js after the fact, it will break horribly.

You are better off doing something like

var myString = 
   ['line1',
    'line2',
    'line3',
    'line4',
    'line5'].join('\n');

or

var mystring = 
    'line1' + 
    'line2' + 
    'line3' + 
    'line4' + 
    'line5';

Upvotes: 6

Scott Evernden
Scott Evernden

Reputation: 39966

most browsers support this. it's not standards-compliant however

Upvotes: 2

Related Questions