试图在 Javascript 中将回车转换为 <br /> html 标签?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6975787/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 22:33:24  来源:igfitidea点击:

Trying to translate a carriage return into a <br /> html tag in Javascript?

javascript

提问by Mark

I have an XML feed that im pulling via javascript and translating it into something more HTML friendly, but im caught up on how to translate carriage returns into an html br tag

我有一个 XML 提要,我通过 javascript 拉取它并将其翻译成对 HTML 更友好的东西,但我赶上了如何将回车转换为 html br 标签

I tried something like this

我试过这样的事情

text = text.replace('\r','<br />'); 

to no avail..

无济于事..

Any ideas?

有任何想法吗?

回答by Ash Burlaczenko

Javascript's replace function only replaces the first occurence if you use a string as the matching criteria. To replace all you can use regex.

如果您使用字符串作为匹配条件,Javascript 的替换功能只会替换第一次出现。要替换所有可以使用的正则表达式。

Try something like this

尝试这样的事情

text = text.replace(/(\r\n|\n|\r)/g,"<br />");

Hope this helps.

希望这可以帮助。

回答by Jean-Baptiste Lemée

You could just apply CSS white-space:preon the element, exactly like the HTML <textarea>element is internally doing:

您可以只white-space:pre在元素上应用 CSS ,就像 HTML<textarea>元素在内部所做的那样:

<span style="white-space:pre">your  text  \n will \n be \n on multiple \n lines</span>

(note: a class is more recommended than style, the above is just a kickoff example)

(注意:类比样式更推荐,以上只是一个启动示例)

回答by Paul

There could be newline characters instead of carriage returns. I would use this:

可能有换行符而不是回车符。我会用这个:

text = text.replace(/\r\n?|\n/g, '<br />');

Which will replace all instances of \r\n, \r, and \nwith a <br />, but won't replace \r\nwith two breaks, which is desired behaviour.

将取代的所有实例\r\n\r以及\n<br />,但不会取代\r\n有两处断裂,这是期望的行为。

回答by Andrey Butov

Try this:

试试这个:

text = text.replace(/\r\n|\r|\n/g, '<br />');

回答by Veger

You should take a look at the feed manually. It probably uses another end of line (EOL) type than \r.

您应该手动查看提要。它可能使用另一种行尾 (EOL) 类型而不是\r.

Also to replace all occurrences of the EOL type, you need to use a regex in the replace()function. Once you have found the correct EOL type, use it like this:

同样要替换所有出现的 EOL 类型,您需要在replace()函数中使用正则表达式。找到正确的 EOL 类型后,请像这样使用它:

text = text.replace(/<type here>/g, '<br />');

(of course you need to replace <type here>with your found EOL type.

(当然,您需要替换<type here>为您找到的 EOL 类型。