views:

228

answers:

2

I've got a copy-clipboard icon on a website, which, when clicked, invokes the following JavaScript (among other):

var hasInnerText = (document.getElementsByTagName("body")[0].innerText != undefined) ? true : false;
var elem = document.getElementById(codeID); 
var content;

// strip out all html tags and just get the text
if (!hasInnerText) { 
 content = elem.textContent;
 content = content.replace(/\xA0/g,' ');
}
else { // ie check
 content =  elem.innerText;
}

This works fine in IE and Firefox, but not in Safari and Chrome. I assume this has something to do with their "Webkit" nature. What ends up happening is that I'm getting malformed whitespaces. I can't explain it any other way. The copy-clipboard is for code samples, and in IE and Firefox, copied code compiles. In Safari/Chrome, it does not.

My assumption is that the content.replace is not being done correctly. Is there another, more appropriate RegEx that I should be doing?

Thanks in advance!

EDIT: I fixed the problem. There's a VERY peculiar issue which I can't believe has gone unnoticed for Chrome/Safari (so maybe something on my end?).

I tried doing a simple alert:

// strip out all html tags and just get the text
    if (!hasInnerText) { 
     content = elem.textContent;
     alert(content);

     content = content.replace(/ /g,' ');
    }

Which for some bloody reason wouldn't work in Chrome/Safari. BUT, when I pulled that alert outside of the if statement, it DID work. Following this line of thought, I pull the content.replace outside as well, and lo and behold, it worked. My code is stripping whitespace as expected.

Someone should explain to me how this is, or if it's a known issue. Or maybe the right persons to contact.

A: 

I'm not exactly sure what that regex is supposed to be doing.. Can you elaborate on that?

If you merely want to condense the whitespace, this should be fine:

 content = content.replace(/\s+/g,' ');
Paul Irish
Single space characters are being translated incorrectly for Chrome/Safari/Firefox. The regex is supposed to remove space entities (\xA0 in hex; I've also tried with nbsp; and  ) with a single space ' '
GJTorikian
A: 

Have you tried replacing \xA0 with  ?

ChaosPandion