javascript - 换行字符串

标签 javascript jquery css

我有一个从 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.

我想知道是否有一个 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.

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

我试过 word-break:break-word; 但这只是将行拆分为没有空格的较长字符串。 我也尝试过 white-space: nowrap; 但是这实际上只是不换行。

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

任何帮助都会很棒!

最佳答案

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

您需要 pre 之一white-space 的选项属性(property)。

/* 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;

关于差异的一些说明:

  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 ")

关于javascript - 换行字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18029892/

相关文章:

javascript - XO 游戏无法正常运行

javascript - 如何使用 Bootstrap 显示另一个导航栏而不是下拉菜单

html - 没有悬停的Webkit过渡

javascript - JQuery toFixed 不是一个函数

javascript - 我可以加载多个模型以使用 AFrame 的 AR 标记来激活吗?

javascript - 如何让在透明 Canvas 上移动的图像不留下移动图像的痕迹/"tracks"?

php - 使用 phonegap 提交带有数据和图像的表单

php - 使用 $.getJSON 将数组发送到服务器端

javascript - JS/DOM 优化 : using :after content styling instead of altering innerHTML

css - 带有 z-index 和位置 :fixed 的非常奇怪的 chrome 错误