2

Using JavaScript, I'm going through an array of objects. If the object has 1 or more values that are not null or empty, a <p> element is created and then appended to the container element.

var tempElem = document.createElement("P");

if( item.valueOne !== '' )
    tempElem.innerHTML += item.valueOne;
if( item.valueTwo !== '' )
    tempElem.innerHTML += item.valueTwo;

if( tempElem.innerHTML !== '' )
    containerElem.appendChild(tempElem);

The above does filter out most empty entries, however a few are somehow making it through to the page.
On chrome, it shows exactly <p></p>
I've done some analyzing, and before the last if-statement...

typeof tempElem.innerHTML = string
tempElem.innerHTML.length = 4
tempElem.innerHTML.charCodeAt(0) = 1
tempElem.innerHTML.charCodeAt(1) = 1
tempElem.innerHTML.charCodeAt(2) = 1
tempElem.innerHTML.charCodeAt(3) = 1
tempElem.innerHTML.charCodeAt(4) = NaN

I'm quite lost on this one. The actual data is in json and for these particular values, I'm seeing key:"". Which is exactly the same as the ones that are being filtered just fine.

I know I can check the values in javascript before creating any kind of dom element, but I'd like to know what's causing this and how to fix it directly.

House3272
  • 1,007
  • 5
  • 14
  • 29
  • According to [ascii-code.com](http://www.ascii-code.com/): 1 is a Start of Header character. Have you tried utilizing [String.prototype.trim()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)? – Sᴀᴍ Onᴇᴌᴀ Sep 18 '16 at 00:30
  • Yup. All my data has that called on it before it gets saved actually. I just tested it out and `trim()` does not take off ascii 1. – House3272 Sep 18 '16 at 00:36
  • Avoid `innerHTML` (it's non-standard, is expensive, and has side-effects). Consider using `textContent` instead. It might also solve this issue you're having. – Dai Sep 18 '16 at 00:50
  • Expensive? I know of the other two negatives, but never heard about it being expensive before. – House3272 Sep 18 '16 at 00:52

1 Answers1

0

Turns out it was due to my usage of the .trim() method.
STRING.trim() does not remove characters such as x00 (Start of Header), x01 (Start of Text), etc.
If present in an otherwise empty string however, these characters will still pass a ==="" check.

For my specific purposes, this simple regex fixes the issue:
str.match(/[^\x00-\x20\x7F]/)
(will return true if at least 1 non space or 'empty' character exists)

House3272
  • 1,007
  • 5
  • 14
  • 29