Replacing   from javascript dom text node

Viewed 132637

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?

10 Answers

A way to hack this in is to replace any empty line with two or more spaces with some newlines and a token. Then post markdown, replace paragraphs with just that token to line breaks.

// replace empty lines with "EMPTY_LINE"
rawMdText = rawMdText.replace(/\n  +(?=\n)/g, "\n\nEMPTY_LINE\n");
// put <br> at the end of any other line with two spaces
rawMdText = rawMdText.replace(/  +\n/, "<br>\n");

// parse
let rawHtml = markdownParse(rawMdText);

// for any paragraphs that end with a newline (injected above) 
// and are followed by multiple empty lines leading to
// another paragraph, condense them into one paragraph
mdHtml = mdHtml.replace(/(<br>\s*<\/p>\s*)(<p>EMPTY_LINE<\/p>\s*)+(<p>)/g, (match) => {
  return match.match(/EMPTY_LINE/g).map(() => "<br>").join("");
});

// for basic newlines, just replace them
mdHtml = mdHtml.replace(/<p>EMPTY_LINE<\/p>/g, "<br>");

What this does is finds every new line with nothing but a couple spaces+. It uses look ahead so that it starts at the right place for the next replace, it'll break on two lines in a row without that.

Then markdown will parse those lines into paragraphs containing nothing but the token "EMPTY_LINE". So you can go through the rawHtml and replace those with line breaks.

As a bonus, the replace function will condense all line break paragraphs into an uppper and lower paragraph if they exist.

In effect, you'd use it like this:

A line with spaces at end  
  
  
and empty lines with spaces in between will condense into a multi-line paragraph.

A line with no spaces at end
  
  
and lines with spaces in between will be two paragraphs with extra lines between.

And the output would be this:

<p>
  A line with spaces at end<br>
  <br>
  <br>
  and empty lines with spaces in between will condense into a multi-line paragraph.
</p>

<p>A line with no spaces at end</p>
<br>
<br>
<p>and lines with spaces in between will be two paragraphs with extra lines between.</p>

This goes through every value in an array of objects and converts

Maybe this helps someone ...Pure javascript function.

var array = [{text: 'test &amp; & "', id:1}, {text: 'test222 &quot; \' 22222 "', id:2}];

    console.log('in', JSON.stringify(array));
    
array.map((object, i) => {
            //console.log('i', i, object);
            Object.keys(object).map(key => {
                var value = String(object[key]);
                
                var replacewith = {'&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"', '&#039;': '\''};
                
                ['&amp;', '&lt;', '&gt;', '&quot;', '&#039;'].map(checkme => {
                    if(value.indexOf(checkme) != -1){
                        console.log('htmlConvertBack found ' + checkme, value);
                        
                        var re = new RegExp(checkme, 'g');
                        
                        object[key] = value.replace(re, replacewith[checkme]);
                    }
                });

            });
        });
    
    console.log('out', JSON.stringify(array));

Related