How to break strings on more than one line without concatenating?

Asked

Viewed 2,332 times

2

Whenever you need to write something very soon in a string in Javascript I need to concatenate, something like:

var str = 'foo bar foo bar foo bar foo bar foo bar foo bar' +
          'foo bar foo bar foo bar foo bar foo bar foo bar' +
          'foo bar foo bar foo bar foo bar foo bar foo bar' +
          'foo bar foo bar foo bar foo bar foo bar foo bar' +
          'foo bar foo bar foo bar foo bar foo bar foo bar'
;

However having to create quotation marks (") or apostrophe ', it is possible to break a string without concatenating?

1 answer

4


As this response from Soen is possible using the backslash

This:

var str = "foo bar foo bar foo bar foo bar foo bar foo bar \
foo bar foo bar foo bar foo bar foo bar foo bar";

Will result in:

foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar

This:

var str = "foo\
bar";

Will result in:

obar

To break also the lines of the "value" it will be necessary to use \n and \ next:

var str = "foo bar foo bar foo bar foo bar foo bar foo bar \n\
foo bar foo bar foo bar foo bar foo bar foo bar";
  • you create the post yourself and you answer in less than 10 minutes? rs

  • 3

    @Rafaelacioly actually no, if you notice at the time of creating a question there is a checkbox for you to open an answer field, this is for when we just want to aggregate new content and is a normal practice of SE sites, see this link: http://en.stackoverflow.com/help/self-answer -- Unfortunately I have already had 2 questions with negative votes because some users think that this practice is wrong :( unfortunately few read the Help Center -- Thanks for the upvote!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.