Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering "whitespace-only" strings in JavaScript

I have a textbox collecting user input in my JS code. I would like to filter junk input, like strings that contain whitespaces only.

In C#, I would use the following code:

if (inputString.Trim() == "") Console.WriteLine("white junk");
else Console.WriteLine("Valid input");

Do you have any recommendation, how to do the same in JavaScript?

like image 948
user68357 Avatar asked Dec 17 '09 13:12

user68357


3 Answers

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

Until the other browsers 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');
like image 122
bobince Avatar answered Oct 23 '22 09:10

bobince


Use a regular expression:

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

or even easier:

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

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

like image 13
Mark Byers Avatar answered Oct 23 '22 09:10

Mark Byers


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

like image 2
Skilldrick Avatar answered Oct 23 '22 09:10

Skilldrick