本文介绍了在JavaScript中替换换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用我的json对象中的 \r \\\
code>< br /> 在网站上显示。

I am trying to replaces instances of \r or \n characters in my json object with <br /> for display on a website.

我试过:

myString = myString.replace("\\r?\\n", "<br />");

但是这似乎没有任何作用。当我用其他东西替换正则表达式(例如a时,替换按预期方式工作)。任何想法为什么这不适用于换行符?

But this doesn't seem to do anything. When I replace the regex with something else (like "a" for instance, the replace works as expected). Any ideas why this isn't working for the newline chars?

推荐答案

尝试这样:

myString = myString.replace(/[\r\n]/g, "<br />");

更新
正如Pointy在下面的评论,这将用两个< br /> 替代一个 \r\\\
正则表达式应该是:

Update:As told by Pointy on the comment below, this would replace a squence of \r\n with two <br />, the correct regex should be:

myString = myString.replace(/\r?\n/g, "<br />");

这篇关于在JavaScript中替换换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 08:45