12

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?

user68357
  • 265
  • 1
  • 3
  • 9

4 Answers4

18

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');
bobince
  • 528,062
  • 107
  • 651
  • 834
13

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'.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
2

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

Skilldrick
  • 69,215
  • 34
  • 177
  • 229
1
function trim (myString)
{
    return myString.replace(/^\s+/,'').replace(/\s+$/,'')
} 

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

Jerome Cance
  • 8,103
  • 12
  • 53
  • 106