Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing non-break-spaces in JavaScript

I am having trouble removing spaces from a string. First I am converting the div to text(); to remove the tags (which works) and then I'm trying to remove the "&nbsp" part of the string, but it won't work. Any Idea what I'm doing wrong.

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>
like image 829
user2014429 Avatar asked Oct 23 '13 18:10

user2014429


2 Answers

When you use the text function, you're not getting HTML, but text: the &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; do the replacement before the conversion to text:

newStr = $($('#myDiv').html().replace(/&nbsp;/g,'')).text();
like image 101
Denys Séguret Avatar answered Sep 18 '22 22:09

Denys Séguret


.text()/textContent do not contain HTML entities (such as &nbsp;), these are returned as literal characters. Here's a regular expression using the non-breaking space Unicode escape sequence:

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.


Below is my original answer, where I've misinterpreted OP's use case. I'll leave it here in case anyone needs to remove &nbsp; from DOM elements' text content

[...] However, be aware that re-setting the .html()/innerHTML of an element means trashing out all of the listeners and data associated with it.

So here's a recursive solution that only alters the text content of text nodes, without reparsing HTML nor any side effects.

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

Demo

like image 38
Fabrício Matté Avatar answered Sep 16 '22 22:09

Fabrício Matté