简体   繁体   English

删除javascript中的非中断空格

[英]removing non-break-spaces in javascript

I am having trouble removing spaces from a string. 我在从字符串中删除空格时遇到问题。 First I am converting the div to text(); 首先我将div转换为text(); to remove the tags(which works) and then I'm trying to remove the " &nbsp " part of the string, but it wont work. 删除标签(有效),然后我试图删除字符串的“ &nbsp ”部分,但它不会工作。 Any Idea what I'm doing wrong. 我知道我做错了什么。 Thanks. 谢谢。

newStr = $('#myDiv').text();
newStr = newStr.replace(/ /g,'');

$('#myText').val(newStr);


<html>
  <div id = "myDiv"><p>remove&nbsp;space</p></div>
  <input type = "text" id = "myText" />
</html>

When you use the text function, you're not getting HTML but text : the &nbsp; 当您使用text功能时,您不会获得HTML而是文字: &nbsp; entities have been changed to spaces. 实体已更改为空格。

So simply replace spaces : 所以简单地替换空格:

 var str = " a     b   ", // bunch of NBSPs newStr = str.replace(/\\s/g,''); console.log(newStr) 

If you want to replace only the spaces coming from &nbsp; 如果您只想更换来自&nbsp;的空格 do the replacement before the conversion to text : 在转换为文本之前进行替换:

newStr = $($('#myDiv').html().replace(/&nbsp;/g,'')).text();

.text() / textContent do not contain HTML entities (such as &nbsp; ), these are returned as literal characters. .text() / textContent不包含HTML实体(例如&nbsp; ),它们作为文字字符返回。 Here's a regular expression using the non-breaking space Unicode escape sequence: 这是使用非中断空格 Unicode转义序列的正则表达式:

var newStr = $('#myDiv').text().replace(/\u00A0/g, '');
$('#myText').val(newStr);

Demo 演示

It is also possible to use a literal non-breaking space character instead of the escape sequence in the Regex, however I find the escape sequence more clear in this case. 也可以使用文字不间断空格字符而不是正则表达式中的转义序列,但是在这种情况下我发现转义序列更清晰。 Nothing that a comment wouldn't solve, though. 但是,评论不会解决任何问题。

It is also possible to use .html() / innerHTML to retrieve the HTML containing HTML entities, as in @Dystroy's answer. 也可以使用.html() / innerHTML来检索包含HTML实体的HTML,如@Dystroy的答案。


Below is my original answer, where I've misinterpreted OP's use case. 以下是我的原始答案,我误解了OP的用例。 I'll leave it here in case anyone needs to remove &nbsp; 我会留在这里以防万一有人需要删除&nbsp; from DOM elements' text content 来自DOM元素的文本内容

[...] However, be aware that re-setting the .html() / innerHTML of an element means trashing out all of the listeners and data associated with it. [...]但是,请注意,重新设置元素的.html() / innerHTML意味着删除所有与之关联的侦听器和数据。

So here's a recursive solution that only alters the text content of text nodes, without reparsing HTML nor any side effects. 所以这里是一个递归解决方案,只改变文本节点的文本内容,而不重新分析HTML或任何副作用。

function removeNbsp($el) {
  $el.contents().each(function() {
    if (this.nodeType === 3) {
      this.nodeValue = this.nodeValue.replace(/\u00A0/g, '');
    } else {
      removeNbsp( $(this) );
    }
  });
}
removeNbsp( $('#myDiv') );

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM