如何删除   和 <br> 使用 javascript 还是 jQuery?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2513848/
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-23 00:41:58  来源:igfitidea点击:

how to remove &nbsp; and <br> using javascript or jQuery?

javascriptjquery

提问by shaz

I have written the following code. But it is removing only &nbsp;not <br>

我已经编写了以下代码。但它只是删除&nbsp;<br>

var docDesc = docDescription.replace(/(&nbsp;)*/g,"");
var docDesc1 = docDescription.replace(/(<br>)*/g,"");

回答by Boldewyn

You can achieve removing <br>with CSS alone:

您可以<br>单独使用 CSS实现删除:

#some_element br {
  display: none;
}

If that doesn't fit your needs, and you want to really delete each <br>, it depends, if docDescriptionis really a string (then one of the above solutions should work, notably Matt Blaine's) or a DOM node. In the latter case, you have to loop through the br elements:

如果这不符合您的需求,并且您想真正删除 each <br>,这取决于它是否docDescription真的是一个字符串(那么上述解决方案之一应该可以工作,特别是 Matt Blaine 的)或 DOM 节点。在后一种情况下,您必须遍历 br 元素:

//jquery method:
$('br').remove();

// plain JS:
var brs = common_parent_element.getElementsByTagName('br');
while (brs.length) {
  brs[0].parentNode.removeChild(brs[0]);
}

Edit:Why Matt Baline's suggestion? Because he also handles the case, where the <br>appears in an XHTML context with closing slash. However, more complete would be this:

编辑:为什么是马特巴林的建议?因为他也处理这种情况,即<br>出现在 XHTML 上下文中并带有斜杠。但是,更完整的是:

/<br[^>]*>/

回答by Yann Saint-Dizier

Try:

尝试:

var docDesc = docDescription.replace(/[&]nbsp[;]/gi," "); // removes all occurrences of &nbsp;
docDesc = docDesc.replace(/[<]br[^>]*[>]/gi,"");  // removes all <br>

回答by hallie

Try "\n"...see if it works.

尝试“\n”...看看它是否有效。

回答by Matt Blaine

What about:

关于什么:

var docDesc1 = docDescription.replace(/(<br ?\/?>)*/g,"");

回答by Darin Dimitrov

This will depend on the input text but I've just checked that this works:

这将取决于输入文本,但我刚刚检查过它是否有效:

var result = 'foo <br> bar'.replace(/(<br>)*/g, '');
alert(result);

回答by alex

Try this

尝试这个

var text = docDescription.replace(/(?:&nbsp;|<br>)/g,'');

回答by Zul

You can do it like this:

你可以这样做:

var cell = document.getElementsByTagName('br');
var length = cell.length;
for(var i = 0; i < length; i++) {
    cell[0].parentNode.removeChild(cell[0]);
}

It works like a charm. No need for jQuery.

它就像一个魅力。不需要 jQuery。

回答by ??ng V?n Thanh

I using simple replace to remove &nbsp;and brtag.

我使用简单的替换来删除&nbsp;br标记。

JavaScript

JavaScript

var str = docDescription.replace(/&nbsp;/g, '').replace(/\<br\s*[\/]?>/gi, '');

jQuery

jQuery

Remove brwith remove() or replaceWith()

删除br与删除()或replaceWith()

$('br').remove();

or

或者

$('br').replaceWith(function() {
  return '';
});