可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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> 1 Space</p>
<p> 2 Spaces</p>
<p> 3 Spaces</p>
<p> 4 Spaces</p>
jQuery
$(document).ready(function() {
$('p').text().replace(/ /g, '');
//$('p').html($(this).html().replace(/ /gi,''));
});
jsfiddle - playground http://jsfiddle.net/MrTest/hbvjQ/85/
Any help much appreciated.
Pete
回答1:
You have   in your code instead of
$('p').each(function(){
$(this).html($(this).html().replace(/ /gi,''));
});
http://jsfiddle.net/genesis/hbvjQ/76/
回答2:
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.
回答3:
try
$('p').each(function() {
$(this).html($(this).html().replace(/ /g, ''));
});
or if you wish to delete the   try
$('p').each(function() {
$(this).html($(this).html().replace(' ', ''));
});
also please note that space is
and not   (you are missing ;)
回答4:
Based on bažmegakapa' answer, this can be used on elements containing other elements.
$('p').html(function (i, old) {
return old.replace(/ /g, '')
});
.text()
gets rid of html elements; .html()
does not
回答5:
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(/ /gi, '');
});
<p>No Space</p>
<p> 1 Space</p>
<p> 2 Spaces</p>
<p> 3 Spaces</p>
<p> 4 Spaces</p>
回答6:
You are replaceing the text, but not applying it back. In addition, use $.trim
to get rid of the
$('p').text(function(i,e){
return $.trim(e.replace(/ /g, ''));
});
回答7:
Here is the code:
$('p').each( function() {
var elem = $( this );
elem.html( elem.html().replace( / /g,'' ) );
} );
And here is jsfiddle: http://jsfiddle.net/hbvjQ/62/