Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing   from javascript dom text node

I am processing xhtml using javascript. I am getting the text content for a div node by concatenating the nodeValue of all child nodes where nodeType == Node.TEXT_NODE.

The resulting string sometimes contains a non-breaking space entity. How do I replace this with a regular space character?

My div looks like this...

<div><b>Expires On</b> Sep 30, 2009 06:30&nbsp;AM</div>

The following suggestions found on the web did not work:

var cleanText = text.replace(/^\xa0*([^\xa0]*)\xa0*$/g,"");   var cleanText = replaceHtmlEntities(text);  var replaceHtmlEntites = (function() {   var translate_re = /&(nbsp|amp|quot|lt|gt);/g;   var translate = {     "nbsp": " ",     "amp" : "&",     "quot": "\"",     "lt"  : "<",     "gt"  : ">"   };   return function(s) {     return ( s.replace(translate_re, function(match, entity) {       return translate[entity];     }) );   } })(); 

Any suggestions?

like image 966
user158678 Avatar asked Sep 30 '09 02:09

user158678


People also ask

What is mean of replacing?

1 : to restore to a former place or position replace cards in a file. 2 : to take the place of especially as a substitute or successor. 3 : to put something new in the place of replace a worn carpet.

How do you use replace in a sentence?

"We need to completely replace our old furniture." "The manager quickly replaced his secretary." "She cannot be easily replaced." "We are going to finally replace our old car."


2 Answers

This is much easier than you're making it. The text node will not have the literal string "&nbsp;" in it, it'll have have the corresponding character with code 160.

function replaceNbsps(str) {   var re = new RegExp(String.fromCharCode(160), "g");   return str.replace(re, " "); }  textNode.nodeValue = replaceNbsps(textNode.nodeValue); 

UPDATE

Even easier:

textNode.nodeValue = textNode.nodeValue.replace(/\u00a0/g, " "); 
like image 182
Tim Down Avatar answered Sep 20 '22 09:09

Tim Down


If you only need to replace &nbsp; then you can use a far simpler regex:

var textWithNBSpaceReplaced = originalText.replace(/&nbsp;/g, ' ');

Also, there is a typo in your div example, it says &nnbsp; instead of &nbsp;.

like image 34
bobbymcr Avatar answered Sep 20 '22 09:09

bobbymcr