Search code examples
javascripthtmlconcatenationstringstreamgeany

How to concatenate strings in JavaScript with tabs and carriage returns in Geany?


I'm making an app with dynamic content loader, it's load the content via ajax then change the DOM. I have a structure/schema, my question is how can I to concatenate the strings, I want to keep my code "indentated" for make it easly readable...

Example: enter image description here

How can I achieve that? I need some special scape character or sort of?


Solution

  • You can escape the newline character at the end of each line with a \, though it's generally considered bad practice (because it's very easy to miss an escape in maintaining the code.)

    var page = '\
      <div class="row well">\
        <div class="row info-block">\
          <div class="col-xs-4 logo-container">\
            ' + logo + '\
          </div>\
        </div>\
      </div>';
    

    What you really want is ES6 template strings, though:

    var page = `
      <div class="row well">
        <div class="row info-block">
          <div class="col-xs-4 logo-container">
            ${logo}
          </div>
        </div>
      </div>`;
    

    Template strings allow multiline strings by default and support interpolation (the ${logo} above.)

    Note: there is a difference between the two resulting strings. In the newline-escaped string, the newlines are actually not a part of the resulting string; whereas, they are in the template string example.