Remove ' ' - still trying

2019-03-12 02:48发布

Still looking for a way to delete ' ' from my html code, found number of ways on stackoverlow.com, but neither of those seam to work!

HTML

<p>No Space</p>
<p>&nbsp;1 Space</p>
<p>&nbsp;&nbsp;2 Spaces</p>
<p>&nbsp;&nbsp;&nbsp;3 Spaces</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;4 Spaces</p>

jQuery

$(document).ready(function() {

    $('p').text().replace(/ /g, '');
    //$('p').html($(this).html().replace(/&nbsp;/gi,''));

});

jsfiddle - playground http://jsfiddle.net/MrTest/hbvjQ/85/

Any help much appreciated.
Pete

7条回答
仙女界的扛把子
2楼-- · 2019-03-12 03:10

try

$('p').each(function() {
     $(this).html($(this).html().replace(/ /g, ''));
});

or if you wish to delete the &nbsp try

$('p').each(function() {
      $(this).html($(this).html().replace('&nbsp;', ''));
});

also please note that space is &nbsp; and not &nbsp (you are missing ;)

查看更多
【Aperson】
3楼-- · 2019-03-12 03:12

Based on bažmegakapa' answer, this can be used on elements containing other elements.

$('p').html(function (i, old) {
    return old.replace(/&nbsp;/g, '')
});

.text() gets rid of html elements; .html() does not

查看更多
等我变得足够好
4楼-- · 2019-03-12 03:16

Here's a non-jQuery answer, since using jQuery for such a task is overkill unless you're already using it for something else on your site:

var p = document.getElementsByTagName('p');

Array.prototype.forEach.call(p, function(el) {
  el.innerHTML = el.innerHTML.replace(/&nbsp;/gi, '');
});
<p>No Space</p>
<p>&nbsp;1 Space</p>
<p>&nbsp;&nbsp;2 Spaces</p>
<p>&nbsp;&nbsp;&nbsp;3 Spaces</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;4 Spaces</p>

查看更多
小情绪 Triste *
5楼-- · 2019-03-12 03:19

You have &nbsp in your code instead of &nbsp;

$('p').each(function(){
    $(this).html($(this).html().replace(/&nbsp;/gi,''));
});

http://jsfiddle.net/genesis/hbvjQ/76/

查看更多
对你真心纯属浪费
6楼-- · 2019-03-12 03:19

This one will replace every white-space character:

$('p').text(function (i, old) {
    return old.replace(/\s/g, '')
});

Or if you only want to replace non-breaking spaces:

$('p').text(function (i, old) {
    return old.replace(/\u00A0/g, '')
});

jsFiddle Demo

I am setting the new value using a closure as a parameter for .text().


Please note that HTML entities need a closing ; in the end.

查看更多
Luminary・发光体
7楼-- · 2019-03-12 03:28

Here is the code:

$('p').each( function() {
    var elem = $( this );
    elem.html( elem.html().replace( /&nbsp;/g,'' ) );
} );

And here is jsfiddle: http://jsfiddle.net/hbvjQ/62/

查看更多
登录 后发表回答