换行字符串

Sha*_*ins 2 javascript css jquery

我有一个从github api模块发回的字符串,其格式如下:

Added debug mode for developers

Simply add the class DEBUG to the body and you'll notice little boxes
scattered throughout your site attached to each grid item.
Run Code Online (Sandbox Code Playgroud)

我想知道是否有一个css选项来清除这些行,因为浏览器读取上面的内容,如下所示:

Added debug mode for developers Simply add the class DEBUG to the body and you'll notice little boxes
scattered throughout your site attached to each grid item.
Run Code Online (Sandbox Code Playgroud)

我真的不想用javacsript拆分字符串,但如果我必须,我想我会:)

我试过word-break:break-word;这只是为了更长的字符串分割行没有空格.我也试过,white-space: nowrap;但字面意思是不包装.

如果我控制台记录数据,chrome ?在"开发者"这个词之后有两个字符,这是导致换行的原因,这些是可以通过javascript选择的吗?

任何帮助都会很棒!

jcs*_*nyi 5

你的问题有点不清楚,但我假设你想保留字符串中包含的换行符 - 而不是浏览器默认完全忽略它们.

您需要prewhite-space物业的其中一个选项.

/* Display text exactly as entered */
white-space: pre;

/* Display as entered, plus extra linebreaks as needed for long lines */
white-space: pre-wrap;

/* Display newlines as entered, plus extra linebreaks as needed for long lines */
white-space: pre-line;
Run Code Online (Sandbox Code Playgroud)

关于差异的一些注意事项:

  1. pre相当于将整个事物包装在<pre>标签中.

  2. pre和之间的区别在于pre-wrap是否会根据需要为长行添加额外的换行符.

  3. pre-wrap和之间的区别在于是pre-line保留所有空格(包括空格)还是仅保留换行符.

  4. pre-line是用<br>标签替换所有换行符的等价物.

你可以在这里看到不同风格的比较:http://jsfiddle.net/Gcexh/


您将遇到的另一个问题是,当您可能不一定要在那里进行换行时,您在输入的最后两行之间有换行符.

您可以通过删除任何单个换行符来解决这个问题,并且只保留双重换行符,例如分隔前两行的双换行符.

理想情况下,这可以在服务器端完成,但也可以在这样的javascript中完成:(
感谢@JanDvorak):

text = text.replace(/(\n\s*\n)|\n/g, "$1 ")
Run Code Online (Sandbox Code Playgroud)