1

I'm trying to build code snippets and output them using clipboard.js. I need to preserve the whitespace in the string to maintain the code indents. I'm providing the code below in ES5 - the behavior is the same for ES6 using string literals. For instance, I have this:

var foo = '<td align="left" valign="top">\n  <img src="img/blob.jpg />\n</td>';

Which outputs this to the console:

<td align="left" valign="top">
  <img src="img/blob.jpg />
</td>

But when I embed 'foo' in another code snippet like this:

 '<table border="0" cellpadding="0" cellspacing="0">' + '\n  <tr>' + '\n    ' +  foo  + '\n  </tr>' +  '\n</table>';

I get this in the console:

<table border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td align="center" valign="top">
      <table border="0" cellpadding="0" cellspacing="0">
        <tr>
      <td align="left" valign="top">
  <img src="img/blob.jpg />
</td>
        </tr>
      </table>
    </td>
    </tr>
</table>

I've tried using the Unicode non-breaking space \xa0 instead of the space character -- no difference. I have a workaround, i.e.:

foo = foo.replace('<img', '    <img');
foo = foo.replace('</td', '    </td');

Which outputs this:

<table border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td align="left" valign="top">
      <img src="img/blob.jpg />
    </td>
  </tr>
</table>

But it requires me to manipulate the whitespace for each output string differently, which means that if I have an embedded table within another table, I have manipulate 'foo' with if-then conditionals for each context in which it will be output. I can do that, but besides the fact that it's hacky, I don't understand this whitespace behavior which is super-annoying.

I'd appreciate any help with how I can avoid the hacky workaround, or even an explanation would be great.

VanAlbert
  • 2,299
  • 1
  • 21
  • 17
  • 1
    A newline *always* returns to the far left side. – Pointy Feb 16 '20 at 14:04
  • 3
    Option 1. just use an HTML formatter. Option 2. You don't care about it as whitespace doesn't matter for HTML – VLAZ Feb 16 '20 at 14:05
  • @Pointy - I'm embarrassed I didn't see that myself... That's the answer if you want the Accept. – VanAlbert Feb 16 '20 at 14:13
  • @VLAZ -- It's for an HTML Email tool where you get tons of deeply embedded tables. Having clean indents is critical. Plus, I'm sure other users of the tool would complain about the messy indents once it's released. An HTML formatter isn't really an option because the tool will be used to build code - can't constantly reformat the code while building it. Thanks for the input, though. – VanAlbert Feb 16 '20 at 14:18
  • 1
    1. Build the code 2. Format before output. Yes, it's slightly more processing but it's less work than reinventing the formatting tool. – VLAZ Feb 16 '20 at 14:20
  • @VLAZ - Ah...I see. Something like this? https://jsfiddle.net/buksy/rxucg1gd/ DO you have something you could recommend? – VanAlbert Feb 16 '20 at 14:26

0 Answers0