Edit: This is the code where I will apply the split:
A have a code snippet surrounded inside pre tags
<pre class="codeSample">
public class Foo
{
}
public class Bar
{
}
</pre>
and here is my jquery code:
var content = $('.codeSample').html();
$('codeSample').html(''); //Clear to ready for new output
var preTag = $('.codeSample');
var lines = content.split('\n');
for(i=0;i<lines.length;i++)
preTag.append('<div>' + lines[i] + '</div>');
The output is this when rendered by the browser:
public class Foo
{
}
public class Bar
{
}
The extra empty line between the two classes is gone.
Edit:
Right now, the following is my solution to fix this:
var content = $('.codeSample').html().replace(/\n(?=\n)/g, '\n ');
This code looks for two consecutive \n and inserts a blank space between them. Now when I do the split, empty lines are included in the array result but they contain a blank space in them. Any alternatives? Thanks.
Edit:
Okay, I will just consider my own solution. Thanks for the replies.
alert(output)at the end of your code. (\nis counted as new line in that case, unlike in HTML.) I also initialized at the beginning withoutput="";On another note, best practice with arrays is to iterate with aforloop."Line1\nLine2\n\nLine3".split("\n")produces an array with four elements, the third of which is an empty string.lines.lengthis 4. What are you actually doing withoutput? (I assume your code is a cut-down example from a more complicated function, because splitting the string only to join it back up with the same separator is pointless.) @david - this question is different to the "duplicate" you linked to.