Home > Blockchain >  JS: How to make multiline strings appear on one line?
JS: How to make multiline strings appear on one line?

Time:01-17

I have a string in my JS code that I want to include three parts, each rendered conditionally.

let a = `
    ${condition1 ? <text1> : ""}
    ${condition2 ? <text2> : ""}
    ${condition3 ? <text3> : ""}
`

I want a to be all on one line, but this renders on multiple lines. The reason I wrote the code on multiple lines is for ease of reading.

Is there a way to write the code on multiple lines but have the string render on one?

CodePudding user response:

Avoid template string literals

let a  = (condition1 ? <text1> : "")
         (condition2 ? <text2> : "")
         (condition3 ? <text3> : "");

Example:

let a  = (true ? "text1" : "")
         (false ? "text2" : "")
         (true ? "text3" : "");
    
console.log(a);

CodePudding user response:

You could simply add backslashes (\) after each line.

const condition1 = true, 
      condition2 = true, 
      condition3 = true;

let a = `\
${condition1 ? 'text1' : ""} \
${condition2 ? 'text2' : ""} \
${condition3 ? 'text3' : ""}
`;

console.log(a)

Hint: Ensure that you remove spaces.

  • Related