0

How can I rewrite the following to do the same thing but to also support trim() for IE.

var isAnonymous = settings.requester_name == null || settings.requester_name.trim() == "";
NoDataDumpNoContribution
  • 10,591
  • 9
  • 64
  • 104

3 Answers3

0

Try:

var isAnonymous = !settings.requester_name || !settings.requester_name.trim();

And you can use this polyfill:

if (!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^[\s\xA0]+|[\s\xA0]+$/g, '');
  };
}
CD..
  • 72,281
  • 25
  • 154
  • 163
0

You can use as below, if trim() is not supported

function myTrim(x) {
   return x.replace(/^\s+|\s+$/gm,'');
}

function myFunction() {
   var str = myTrim("        Hello World!        ");
   alert(str);
}

Demo

Amit
  • 15,217
  • 8
  • 46
  • 68
-1

In Javascript an empty string is a falsy value, so is null or undefined, given that the following should work

var isAnonymous = !settings.requester_name || !settings.requester_name.trim()

The second part of the expression converts the empty string into a boolean, which evaluates false if empty.

What version of IE are you using? Trim has been supported for a while...

If you are writing for older than ie9 you can add a polyfill for trim

if (!String.prototype.trim) {
   String.prototype.trim = function () {
     return this.replace(/^[\s\xA0]+|[\s\xA0]+$/g, '');
   };
}    

FFR: Mozilla developer network is a great source for Javascript app docs, and they include polyfill implementations you can use for old browser support.

Heres the docs for trim (the polyfill may look familiar) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim

Jason
  • 15,915
  • 3
  • 48
  • 72
  • Did you even read the question? According to your edit, you didn't. He's trying to get support for IE < 9, the only IE versions that don't natively support it. – Chris Cirefice Sep 16 '14 at 13:05
  • Calm down homeboy, it doesn't say ie9 anywhere I the question. – Jason Sep 16 '14 at 13:11
  • Your original answer had nothing to do with his question... on top of that, you put the exact same code as CD's answer into yours, 5 minutes later. – Chris Cirefice Sep 16 '14 at 13:13