Remove   from html

Remove   from html

本文关键字:from html nbsp Remove amp      更新时间:2023-09-26

我想从下面的代码中删除 

<div class="country-IN">
   <span class="locality">Barnala</span>
   &nbsp;&nbsp;
   <span class="state">Punjab</span>
   &nbsp;&nbsp;
   <span class="country">India</span>
</div>

请帮我摆脱它。

我建议:

var el = document.querySelector('.country-IN');
el.innerHTML = el.innerHTML.replace(/&nbsp;/g,'');

JS Fiddle demo.

或者,使用jQuery:

$('.country-IN').html(function(i,h){
    return h.replace(/&nbsp;/g,'');
});

JS Fiddle demo.

甚至:

$('.country-IN').children().each(function(i,e){
    this.parentNode.removeChild(this.nextSibling);
});

JS Fiddle demo.

虽然简单地编辑HTML文件本身并删除这些字符串会更容易。

你可以得到你想要的元素,并将其添加回元素的html

$('.country-IN').html(function(i,v){
   return $('<div>').append($(this).children('*')).html(); 
});

小提琴

Library不可知论:

(function() {
var country_els = document.querySelectorAll('.country-IN');
for (var i = 0; i < country_els.length; i++) {
    for (var j = 0; j < country_els[i].childNodes.length; j++) {
        var node = country_els[i].childNodes[j];
        if (typeof node.tagName === 'undefined') {
            node.parentNode.removeChild(node);
        }
    }  
}
})();

小提琴

首先,获取整个HTMLdiv并将其转换为字符串

convertHtmlToText(str)
{
   str = str.toString();
  return str.replace(/<[^>]*(>|$)|&nbsp;|&zwnj;|&raquo;|&laquo;|&gt;/g, ' ');
}

你会得到没有HTML标签和&nbsp等的文本

您可以在上述解决方案中添加多个条件

我们不需要javascript。我们可以只用CSS隐藏&nbsp;。将font-size: 0添加到容器中,将font-size: 1rem添加到子容器中

.second {
  font-size: 0;
}
.second > span {
  font-size: 1rem;
}
<div class="country-IN">
  <span class="locality">Barnala</span>
  &nbsp;&nbsp;
  <span class="state">Punjab</span>
  &nbsp;&nbsp;
  <span class="country">India</span>
</div>
<div class="country-IN second">
  <span class="locality">Barnala</span>
  &nbsp;&nbsp;
  <span class="state">Punjab</span>
  &nbsp;&nbsp;
  <span class="country">India</span>
</div>

可以在PHP中使用preg_replace。

<?php
$html = "YOUR HTML"
$new = preg_replace("!&nbsp;!", "", $html);
print($new);
?>

我以前使用过这个脚本,它应该可以正常工作。