Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare a string var with multiple lines in JavaScript/jQuery

How do i declare a variable in jquery with multiple lines like,

original variable:

var h = '<label>Hello World, Welcome to the hotel</label><input type="button" value="Visit Hotel"><input type="button" value="Exit">';

the variable i want to declare:

var h = '<label>Hello World, Welcome to the hotel</label>
              <input type="button" value="Visit Hotel">
              <input type="button" value="Exit">';
like image 279
Chris Avatar asked Jan 18 '14 10:01

Chris


People also ask

How do you write a multi line string in JavaScript?

There are three ways to create strings that span multiple lines: By using template literals. By using the + operator – the JavaScript concatenation operator. By using the \ operator – the JavaScript backslash operator and escape character.

How do you store several paragraphs of text as a string in JS?

You can do this by using a raw string (put r in front of the string, as in r"abc\ndef" , or by including an extra slash in front of the newline ( "abc\\ndef" ).

What is the delimiter for multi line strings in JavaScript?

Method 1: Multiline-strings are created by using template literals. The strings are delimited using backticks, unlike normal single/double quotes delimiter.

How do you define multiline strings?

Use triple quotes to create a multiline string It is the simplest method to let a long string split into different lines. You will need to enclose it with a pair of Triple quotes, one at the start and second in the end. Anything inside the enclosing Triple quotes will become part of one multiline string.


1 Answers

You can use \ to indicate that the line has not finished yet.

var h= '<label>Hello World, Welcome to the hotel</label> \
              <input type="button" value="Visit Hotel"> \
              <input type="button" value="Exit">';

Note: When you use \, the whitespace in the following line will also be a part of the string, like this

console.log(h);

Output

<label>Hello World, Welcome to the hotel</label>               <input type="button" value="Visit Hotel">               <input type="button" value="Exit">

The best method is to use the one suggested by Mr.Alien in the comments section, concatenate the strings, like this

var h = '<label>Hello World, Welcome to the hotel</label>' +
              '<input type="button" value="Visit Hotel">' +
              '<input type="button" value="Exit">';

console.log(h);

Output

<label>Hello World, Welcome to the hotel</label><input type="button" value="Visit Hotel"><input type="button" value="Exit">
like image 121
thefourtheye Avatar answered Sep 29 '22 19:09

thefourtheye