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

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

问题描述

如何使用Javascript从值中读取换行符并用 br 标记替换所有换行符?

How can I read the line break from a value with Javascript and replace all the line breaks with br tags?

示例:

从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天全站免登陆