mathiasbynens / he

A robust HTML entity encoder/decoder written in JavaScript.
https://mths.be/he
MIT License
3.45k stars 254 forks source link

[he.encode] Avoid error if arg string is null #26

Closed lyrad closed 9 years ago

lyrad commented 10 years ago

Hi, good library! But I don't want to test if my string is null or not before to he.encode it (lazy boy :)). The strings coming from left jointed sql requests are often null...

So I add, line 139, just after "var encode = function(string, options) { ... " if(string === null)return '';

RastoStric commented 9 years ago

Such a nice library and it falls on null? Uauuu, this should not happen... Now I have to have multiple times in my code if(... null) instead of one if in the library... Please do it... Thank you!

anko commented 9 years ago

I think it's reasonable for a library to fail when given an input without an "obviously correct" way to handle it. Encoding null"null" seems a sensible interpretation too.

Numbers are also rejected, likely for similar reasons.

To specify your own logic for the null case and avoid repeating the check in your other code, you could create a simple wrapper function in your code:

var he = function(string, opt) { return string === null ? "" : he(string, opt) };

Then just use he as you would otherwise.

mathiasbynens commented 9 years ago

Agreed with @anko (although you’d use he.encode or he.decode instead of he directly). null"null" is a reasonable expectation as well. Use he as documented and create a wrapper as needed.

lyrad commented 9 years ago

Okay, After all, encoding null string should fail... I'll use a wrapper, Thx!

catmeme commented 8 years ago

This tip helped me out. I wrote my wrapper as such. I'm sure it could be consolidated but thought it might help someone else as is:

function isInt(value) {
  return !isNaN(value) &&
         parseInt(Number(value)) == value &&
         !isNaN(parseInt(value, 10));
}

function isFloat(n) {
    return Number(n) === n && n % 1 !== 0;
}

// Add encodeall method to avoid potential issues
he.encodeall = function(string, opt) {
  if (string === null) {
    return "";
  } else if (isInt(string) || isFloat(string)) {
    return string;
  } else {
    return he.encode(string, opt)
  }
};

now I just use he as such: he.encodeall(null)