简体   繁体   English

Javascript:分割字串时请加入空白行

[英]Javascript: Include empty lines when splitting strings

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: 这是我的jQuery代码:

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. 此代码查找两个连续的\\ n并在它们之间插入一个空格。 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. 感谢您的答复。

The result of the split is ['Line1', 'Line2', '', 'Line3']. 分割的结果 ['Line1','Line2','','Line3']。 Notice the empty string? 注意到空字符串了吗? That's where your extra newline was . 这就是你额外的换行符

You need to turn the empty strings into newlines. 您需要将空字符串转换为换行符。

See: http://jsfiddle.net/Xavura/hKsTj/#run 参见: http : //jsfiddle.net/Xavura/hKsTj/#run

So you want to do something like this: 所以你想做这样的事情:

lines = lines.map(function(i) { return (i === '') ? '\n' : i; });

如果输出的是HTML,则将换行符视为不会显示的空格,如果要在HTML中换行,请使用<br />标记。

With your edit, the problem is now only that an empty <div> tag takes up no vertical space. 通过您的编辑,现在的问题只是空的<div>标记不占用垂直空间。

This can be fixed by setting a minimum height for code lines in your stylesheet: 可以通过为样式表中的代码行设置最小高度来解决此问题:

.codeSample div {
    min-height: 1em;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM