[ACCEPTED]-Filtering "whitespace-only" strings in JavaScript-whitespace

Accepted answer
Score: 18

The trim() method on strings does exist in the 4 ECMAScript Fifth Edition standard and has 3 been implemented by Mozilla (Firefox 3.5 2 and related browsers).

Until the other browsers 1 catch up, you can fix them up like this:

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

then:

if (inputString.trim()==='')
    alert('white junk');
Score: 13

Use a regular expression:

if (inputString.match(/^\s*$/)) { alert("not ok"); }

or even easier:

if (inputString.match(/\S/)) { alert("ok"); }

The 1 \S means 'any non white space character'.

Score: 2

Alternatively, /^\s*$/.test(inputString)

0

Score: 1
function trim (myString)
{
    return myString.replace(/^\s+/,'').replace(/\s+$/,'')
} 

use it like this: if (trim(myString) == "")

0

More Related questions