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

时间:2011-11-09 08:52:42

标签: javascript html

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

3 个答案:

答案 0 :(得分:48)

您正在寻找相当于PHP的br2nl()。这应该做的工作:

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

答案 1 :(得分:1)

便宜的功能:

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

ES。

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

结果是:&#34; Hello / nworld!&#34;

答案 2 :(得分:0)

此功能考虑是否要删除或替换诸如<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);
}

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

Demo - JSFiddle

  

JavaScript nl2br & br2nl functions

相关问题