Skip to content Skip to sidebar Skip to footer

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 = '

Solution 1:

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

var h= '<label>Hello World, Welcome to the hotel</label> \
              <inputtype="button"value="Visit Hotel"> \
              <inputtype="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>               <inputtype="button" value="Visit Hotel">               <inputtype="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>' +
              '<inputtype="button"value="Visit Hotel">' +
              '<inputtype="button"value="Exit">';

console.log(h);

Output

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

Solution 2:

Edit

Now you could also make a use of ES6 Template Literals.

let str = `
  some
  random
  string
`;

You can also interpolate the variables in the above string with an ease, without using concatenation, like:

let somestr = 'hello',
str = `
  ${somestr}
  world
`;

Old answer

@thefourtheye answer is perfect, but if you want, you can also use concatenation here because sometimes \ will be misleading, as you will think those are literal characters ..

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

console.log(h);

Demo

Solution 3:

In ES6 you can achieve this by simply declaring a variable as:

const sampleString  = `Sample
                       text
                       here`;

This in return evaluates to 'Sample \ntext\nhere' You can read all about ES6 rules of multiline strings from here.

Post a Comment for "Declare A String Var With Multiple Lines In Javascript/jquery"