This question already has an answer here:
这个问题已经有了答案:
- How do I replace all line breaks in a string with <br /> tags? 10 answers
-
如何用
标记替换字符串中的所有行中断?10个答案
var messagetoSend = $.trim(document.getElementById("msgText").value);
messagetoSend = messagetoSend.replace("\n", "<br />");
alert(messagetoSend);
Given input:
给定的输入:
Line 1
Line 2
Line 3
This alerts:
这个警报:
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
3 个解决方案
#1
126
You need the /g for global matching
您需要全局匹配的/g。
replace(/\n/g, "<br />");
替换(/ \ n / g,< br / >);
This works for me
这适合我
<textarea id="x">
Line 1
Line 2
Line 3
</textarea>
<script>
var messagetoSend = document.getElementById('x').value.replace(/\n/g, "<br />");
alert(messagetoSend);
</script>
UPDATE
更新
It seems some visitors of this question have text with the breaklines escaped as
似乎有一些人在这个问题上有了文本,但有一些断点。
some text\r\nover more than one line"
一些文本\r\nover不止一行"
In that case you need to escape the slashes:
在这种情况下,你需要逃离斜线:
replace(/\\r\\n/g, "<br />");
替换(/ \ \ r \ \ n / g,< br / >);
NOTE: All browsers will ignore \r
in a string when rendering.
注意:当渲染时,所有浏览器都会忽略\r。
#2
46
Handles either type of line break
处理任何类型的换行。
str.replace(new RegExp('\r?\n','g'), '<br />');
#3
5
Use a regular expression for .replace()
.:
使用正则表达式for .replace()。
messagetoSend = messagetoSend.replace(/\n/g, "<br />");
If those linebreaks were made by windows-encoding, you will also have to replace the carriage return
.
如果这些换行是通过windows编码实现的,你也需要替换回车。
messagetoSend = messagetoSend.replace(/\r\n/g, "<br />");
#1
126
You need the /g for global matching
您需要全局匹配的/g。
replace(/\n/g, "<br />");
替换(/ \ n / g,< br / >);
This works for me
这适合我
<textarea id="x">
Line 1
Line 2
Line 3
</textarea>
<script>
var messagetoSend = document.getElementById('x').value.replace(/\n/g, "<br />");
alert(messagetoSend);
</script>
UPDATE
更新
It seems some visitors of this question have text with the breaklines escaped as
似乎有一些人在这个问题上有了文本,但有一些断点。
some text\r\nover more than one line"
一些文本\r\nover不止一行"
In that case you need to escape the slashes:
在这种情况下,你需要逃离斜线:
replace(/\\r\\n/g, "<br />");
替换(/ \ \ r \ \ n / g,< br / >);
NOTE: All browsers will ignore \r
in a string when rendering.
注意:当渲染时,所有浏览器都会忽略\r。
#2
46
Handles either type of line break
处理任何类型的换行。
str.replace(new RegExp('\r?\n','g'), '<br />');
#3
5
Use a regular expression for .replace()
.:
使用正则表达式for .replace()。
messagetoSend = messagetoSend.replace(/\n/g, "<br />");
If those linebreaks were made by windows-encoding, you will also have to replace the carriage return
.
如果这些换行是通过windows编码实现的,你也需要替换回车。
messagetoSend = messagetoSend.replace(/\r\n/g, "<br />");