Jin*_*ong 503 javascript
如何使用Javascript从值读取换行符并用<br />标签替换所有换行符?
例:
从PHP传递的变量如下:
"This is man.
Man like dog.
Man like to drink.
Man is the king."
Run Code Online (Sandbox Code Playgroud)
在Javascript转换后,我希望我的结果看起来像这样:
"This is man<br /><br />Man like dog.<br />Man like to drink.<br /><br />Man is the king."
Run Code Online (Sandbox Code Playgroud)
eye*_*ess 1126
这会将所有返回值转换为HTML
str = str.replace(/(?:\r\n|\r|\n)/g, '<br>');
Run Code Online (Sandbox Code Playgroud)
如果你想知道什么?:意味着.它被称为非捕获组.这意味着括号内的正则表达式组不会保存在内存中以便稍后引用.您可以查看这些线程以获取更多信息:
https
://stackoverflow.com/a/11530881/5042169 /sf/answers/2556718881/
ber*_*ing 351
如果你关注的只是显示换行符,你可以用CSS做到这一点.
HTML
<div class="white-space-pre">Some test
with linebreaks</div>
Run Code Online (Sandbox Code Playgroud)
CSS
.white-space-pre {
white-space: pre-wrap;
}
Run Code Online (Sandbox Code Playgroud)
jsfiddle https://jsfiddle.net/yk1angkz/125/
Note: Pay attention to code formatting and indenting, since white-space: pre-wrap will display all whitespaces (except for the last newline after the text, see fiddle).
pau*_*r19 70
没有正则表达式:
str = str.split("\n").join("<br />");
Run Code Online (Sandbox Code Playgroud)
WSk*_*ner 36
这适用于来自textarea的输入
str.replace(new RegExp('\r?\n','g'), '<br />');
Run Code Online (Sandbox Code Playgroud)
Afa*_*kin 11
支持最常见的EOL 样式 \r、\n以及\r\n使用 HTML5 的最短代码<br>:
s.replace(/\r?\n|\r/g, '<br>')
Run Code Online (Sandbox Code Playgroud)
如果接受的答案不适合您,那么您可以尝试.
str.replace(new RegExp('\n','g'), '<br />')
Run Code Online (Sandbox Code Playgroud)
它对我有用.
对文本的其余部分进行编码以防止可能的脚本注入攻击也很重要
function insertTextWithLineBreaks(text, targetElement) {
var textWithNormalizedLineBreaks = text.replace('\r\n', '\n');
var textParts = textWithNormalizedLineBreaks.split('\n');
for (var i = 0; i < textParts.length; i++) {
targetElement.appendChild(document.createTextNode(textParts[i]));
if (i < textParts.length - 1) {
targetElement.appendChild(document.createElement('br'));
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
424557 次 |
| 最近记录: |