JavaScript 将 替换为 <br/> [英] JavaScript replace with <br />
本文介绍了JavaScript 将
替换为 <br/>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
var messagetoSend = $.trim(document.getElementById("msgText").value);
messagetoSend = messagetoSend.replace("
", "<br />");
alert(messagetoSend);
给定输入:
Line 1
Line 2
Line 3
此警报:
Line 1<br />
Line 2
Line 3
当我希望它发出警报时:
When I expect it to alert:
Line 1<br /><br /><br />Line 2<br /><br /><br /><br /><br />Line 3
推荐答案
replace(/
/g, "
");
replace(/
/g, "<br />");
这对我来说适用于
- 如果您有 <代码>
This works for me for
- see this answer if you might have
注意: 欺骗是的任何组合的最完整答案
、
或
NOTE: The dupe is the most complete answer for any combination of
,
or
var messagetoSend = document.getElementById('x').value.replace(/
/g, "<br />");
console.log(messagetoSend);
<textarea id="x" rows="9">
Line 1
Line 2
Line 3
</textarea>
更新
似乎这个问题的一些访问者的文本带有转义线的文本
It seems some visitors of this question have text with the breaklines escaped as
一些文本 超过一行"
some text over more than one line"
在这种情况下,您需要对斜线进行转义:
In that case you need to escape the slashes:
replace(/\r\n/g, "
");
注意:所有浏览器在渲染时都会忽略字符串中的
.
NOTE: All browsers will ignore
in a string when rendering.
这篇关于JavaScript 将 替换为 <br/>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文