如何用< br/>替换字符串中的所有换行符元素? [英] How do I replace all line breaks in a string with <br /> elements?

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

问题描述

如何使用JavaScript从值读取换行符并将所有换行符替换为<br />元素?

How can I read the line break from a value with JavaScript and replace all the line breaks with <br /> elements?

示例:

从PHP传递的变量如下:

A variable passed from PHP as below:

  "This is man.

     Man like dog.
     Man like to drink.

     Man is the king."

我希望我的结果在JavaScript转换后看起来像这样:

I would like my result to look something like this after the JavaScript converts it:

  "This is man<br /><br />Man like dog.<br />Man like to drink.<br /><br />Man is the king."

推荐答案

这会将所有返回值转换为HTML

This will turn all returns into HTML

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

如果您想知道什么?:是什么意思. 它称为非捕获组.这意味着括号内的正则表达式组不会保存在内存中以供以后引用. 您可以查看以下线程以获取更多信息:
https://stackoverflow.com/a/11530881/5042169 https://stackoverflow.com/a/36524555/5042169

In case you wonder what ?: means. It is called a non-capturing group. It means that group of regex within the parentheses won't be saved in memory to be referenced later. You can check out these threads for more information:
https://stackoverflow.com/a/11530881/5042169 https://stackoverflow.com/a/36524555/5042169

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

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