Javascript 删除“ ” - 仍在尝试
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6452731/
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
Remove ' ' - still trying
提问by Iladarsda
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 代码中删除的方法,在 stackoverlow.com 上找到了多种方法,但这些接缝都不起作用!
HTML
HTML
<p>No Space</p>
<p> 1 Space</p>
<p> 2 Spaces</p>
<p> 3 Spaces</p>
<p> 4 Spaces</p>
jQuery
jQuery
$(document).ready(function() {
$('p').text().replace(/ /g, '');
//$('p').html($(this).html().replace(/ /gi,''));
});
jsfiddle - playgroundhttp://jsfiddle.net/MrTest/hbvjQ/85/
jsfiddle - 游乐场http://jsfiddle.net/MrTest/hbvjQ/85/
Any help much appreciated.
Pete
非常感谢任何帮助。
皮特
回答by genesis
You have   in your code instead of
你的代码中有 而不是
$('p').each(function(){
$(this).html($(this).html().replace(/ /gi,''));
});
回答by kapa
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, '')
});
I am setting the new value using a closure as a parameter for .text()
.
我正在使用闭包作为.text()
.
Please note that HTML entities need a closing ;
in the end.
请注意,HTML 实体最后需要;
结束。
回答by rnevius
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:
这是一个非 jQuery 答案,因为将 jQuery 用于这样的任务是矫枉过正的,除非您已经将它用于您网站上的其他内容:
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>
回答by fregante
Based on ba?megakapa' answer, this can be used on elements containing other elements.
根据ba?megakapa' answer,这可以用于包含其他元素的元素。
$('p').html(function (i, old) {
return old.replace(/ /g, '')
});
.text()
gets rid of html elements; .html()
does not
.text()
摆脱 html 元素;.html()
才不是
回答by kleinohad
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 ;)
另请注意,空格是
而不是 (您丢失了;)
回答by CoolEsh
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/
这是 jsfiddle:http: //jsfiddle.net/hbvjQ/62/