Skip to content Skip to sidebar Skip to footer

Check Whether White Spaces Exist Without Using Trim

I have following code that checks whether date is valid. http://jsfiddle.net/uzSU6/36/ If there is blank spaces in date part, month part or year part the date should be considered

Solution 1:

You can use indexOf() function if there is space in the date string.

if(s.indexOf(' ') != -1)
{
    //space exists
}

Solution 2:

you can test for any whitespace like

if( /\s/g.test(s) )

it will test any whitespace.

Solution 3:

You may want to consider using a regexp to test your string's validity:

functionisValidDate(s) {
    var re = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
    var mdy = s.match(re);
    if (!mdy) {
        returnfalse;   // string syntax invalid;
    }

    var d = newDate(mdy[3], mdy[1] - 1, mdy[2]);
    return (d.getFullYear() == mdy[3]) &&
           (d.getMonth() == mdy[1] - 1) &&
           (d.getDate() == mdy[2]);
}

The regex does all this in one go:

  • checks that there are three fields separated by slashes
  • requires that the fields be numbers
  • allows day and month to be 1 or 2 digits, but requires 4 for the year
  • ensures that nothing else in the string is legal

See http://jsfiddle.net/alnitak/pk4wU/

Post a Comment for "Check Whether White Spaces Exist Without Using Trim"