Javascript 如何用换行符“\n”替换 HTML <br>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8062399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:34:35  来源:igfitidea点击:

How replace HTML <br> with newline character "\n"

javascripthtml

提问by Anoop

How can I replace HTML <BR> <BR/> or <BR />with new line character "\n"

如何<BR> <BR/> or <BR />用换行符“\n”替换 HTML

回答by Polynomial

You're looking for an equivilent of PHP's br2nl(). This should do the job:

您正在寻找与 PHP 相同的br2nl(). 这应该可以完成这项工作:

function br2nl(str) {
    return str.replace(/<br\s*\/?>/mg,"\n");
}

回答by Andrea_dev

A cheap function:

一个便宜的功能:

function brToNewLine(str) {
    return str.replace(/<br ?\/?>/g, "\n");
}

es.

es.

vat str = "Hello<br \>world!";
var result = brToNewLine(str);

The result is: "Hello/nworld!"

结果是:“你好/nworld!”

回答by Nick Tsai

This function considers whether to remove or replace the tags such as <br>, <BR>, <br />, </br>.

该函数考虑是否删除或替换诸如<br><BR><br />、等标签</br>

/**
 * This function inverses text from PHP's nl2br() with default parameters.
 *
 * @param {string} str Input text
 * @param {boolean} replaceMode Use replace instead of insert
 * @return {string} Filtered text
 */
function br2nl (str, replaceMode) {   

  var replaceStr = (replaceMode) ? "\n" : '';
  // Includes <br>, <BR>, <br />, </br>
  return str.replace(/<\s*\/?br\s*[\/]?>/gi, replaceStr);
}

In your case, you need to use replaceMode. For eaxmple: br2nl('1st<br>2st', true)

在您的情况下,您需要使用replaceMode. 例如:br2nl('1st<br>2st', true)

Demo - JSFiddle

演示 - JSFiddle

JavaScript nl2br & br2nl functions

JavaScript nl2br & br2nl 函数