如何查找换行符并替换为< br> JavaScript中的元素? [英] How do I find line breaks and replace with <br> elements in JavaScript?

查看:151
本文介绍了如何查找换行符并替换为< br> JavaScript中的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用javascript在文本中查找和替换换行符。

I am trying to find and replace line breaks in text using javascript.

以下有效。它用字符z替换字符a。

The following works. It replaces the character a with the character z.

var text = "aasdfasdf";
text= text.replace(/a/g,"z");
alert(text);

以下基于此消息板和其他留言板上的其他帖子没有。基本上javascript不会触发:

The following based on other posts on this and other message boards does not. Basically the javascript does not fire:

var text = "aasdfasdf";
text= text.replace(/\n/g,"z");
alert(text);

...这是许多帖子之一,表明它应该有效。

...Here is one of many posts that suggests it should work.

JavaScript:如何在HTML textarea中添加换行符?

并且以下方式在Firefox中对我不起作用:

and by the way following does not work for me in Firefox either:

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

注意:我意识到文本变量中没有换行符...我只是使用了一个简单的字符串用于测试目的。

Note: I realize there are no line breaks in the text variable..I am just using a simple string for testing purposes.

任何人都可以看到可能出现的问题,或者告诉我一种实际可行的方法。

Can anyone see what could be wrong or show me a way to do this that actually works.

谢谢。

推荐答案

我通过处理 \\\\ n (序列),然后通过字符类处理 \ r \ n ,像这样:

I'd cover my bets by handling \r\n (the sequence), and then handling \r and \n through a character class, like this:

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

第一个替换将转换序列 \\\\ n 进入< br /> 。第二个替换用字符串替换任何 \ r \ n 字符。

The first replace turns the sequence \r\n into <br />. The second replace replaces any \r or \n characters found on their own with the string.

有关JavaScript中正则表达式的更多信息此处

More on regular expressions in JavaScript here.

这篇关于如何查找换行符并替换为&lt; br&gt; JavaScript中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆