jQuery 删除   来自 html

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

Remove   from html

jqueryhtmlcss

提问by Manjit Singh

I want to remove  from the below code.

我想 从下面的代码中删除。

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

Please help me to get out of it.

请帮我摆脱它。

回答by David says reinstate Monica

I'd suggest:

我建议:

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

JS Fiddle demo.

JS小提琴演示

Or, with jQuery:

或者,使用 jQuery:

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

JS Fiddle demo.

JS小提琴演示

Or even:

甚至:

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

JS Fiddle demo.

JS小提琴演示

Though it'd be easier to simply edit the HTML files themselves and just removethose strings of characters.

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

回答by ?????

You can get the elements you want and add it back as the html for the element

您可以获取所需的元素并将其添加回元素的 html

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

FIDDLE

小提琴

回答by Sahil Ralkar

First, get your whole HTML div and convert it to the string

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

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

you will get the text without HTML tag and &nbsp etc

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

you can add multiple conditions in the above solution

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

回答by okcoker

Library agnostic:

图书馆不可知论者:

(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);
        }
    }  
}
})();

Fiddle

小提琴

回答by TimeWasterNL

You can do this with preg_replace in PHP.

你可以用 PHP 中的 preg_replace 来做到这一点。

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

I used this script before and it should work fine.

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