2

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>';
4
  • That looks funny because the backslashes are inside the quotes... which makes me believe that it isn't really a JS thing and those slashes are either being preserved in the string, or... they're escaping the newline. Commented Jul 23, 2010 at 16:42
  • @Mark, they ARE escaping the newline Commented Jul 23, 2010 at 16:43
  • 1
    @Chad: Yeah.. but I mean, it's not the same thing as closing the quote, and then escaping the newline, is it? In one case you're just telling JS that the line continues so it shouldn't work is magic-semi-colon BS, and in the other case, you're saying what should be included in the string, no? Or maybe I'm confusing languages and how they handle these things... Python for instance lets you butt two strings up next to each other and it'll just join em for you. Commented Jul 23, 2010 at 16:51
  • @Chad: Here's what I mean: pastebin.com/kW7CvjMc Commented Jul 23, 2010 at 16:56

3 Answers 3

6

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';
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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

Edit: It's technically an escape character.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.