-1

Below is link to js code

non indented : http://jsfiddle.net/bsr1/ucg6v1v0/

var dataAbc = '<div class="message7">Focus Shifted Here</div>';
alert("*");

indented http://jsfiddle.net/bsr1/1dtrz0au/

var dataAbc = '<div class="message7">
            Focus Shifted Here
        </div>';
alert("*");

I know 2nd one results in an js error.Is there nay way i can indent my js code without erorr

5 Answers5

1

A string cannot be declared across multiple lines.

Option 1 - Concatenate:

var dataAbc = '<div class="message7">' + 
            'Focus Shifted Here' + 
        '</div>';

Option 2 - Escape the newline with a backslash:

var dataAbc = '<div class="message7">\
            Focus Shifted Here\
        </div>';

I would advise against option 2, since it relies on the right amount of whitespace after the \, and is not ideal for minification.

On the bright size, ES6 will introduce template strings.

Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
1

You can indent your JS code. Indeed, everyone will be happy if you do.

However, you cannot break a string into multiple lines like that.

You can cancel a line break in a string by having a backslash \ as the last character:

var dataAbc = '<div class="message7">\
            Focus Shifted Here\
        </div>';

If you also want the newline in the string, you must put it in explicitly:

var dataAbc = '<div class="message7">\n\
            Focus Shifted Here\n\
        </div>';

You can also break up the string and assemble it from parts at runtime:

var dataAbc = '<div class="message7">\n' +
            'Focus Shifted Here\n' +
        '</div>';

However, you cannot have an unescaped linebreak inside a string.

Amadan
  • 191,408
  • 23
  • 240
  • 301
0

What I always do for easy reading is:

var dataAbc = '<div class="message7">'+ 'Focus Shifted Here'+ '</div>'; alert("*");

gyeo
  • 63
  • 6
0

End with \

var dataAbc = '<div class="message7">\
            Focus Shifted Here\
        </div>';
alert("*");

Still, I don't think it's a good idea to insert (complicated) HTML structure in JS.

Leo
  • 13,428
  • 5
  • 43
  • 61
-1

Javascript doesn't have a here-document syntax. You can escape the literal newline, however, which comes close:

"foo \
bar"

Ref taken from this

Community
  • 1
  • 1
Pankaj
  • 571
  • 5
  • 20