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.