gpt4 book ai didi

javascript - 换行字符串

转载 作者:行者123 更新时间:2023-11-29 17:15:52 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com