Design & Download
Your JS Library
in Seconds!!!

Snippet: isSpace() & isWhitespace()

Written by Christopher West (cwest) on August 24, 2016.
Test for whitespace strings and space strings like you can in Java.
var isSpace = isRegExpMatch(/[ \xA0\u1680\u180E\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/),
    isWhitespace = isRegExpMatch(/[\t-\r\x1C- \u1680\u180E\u2000-\u200A\u2028\u2029\u205F\u3000]/);

isSpace(...) API Documentation

Description

Test for space characters starting at the beginning of a string.

Parameters

  1. str {string}:
    The string to be tested.
  2. opt_onlyCheckStart {boolean}:
    Optional. Defaults to false. If true, only the beginning of the string is checked to see if it starts with a space character. If false, all of the string is checked to see if it only contains space characters.

Returns

Returns true if opt_onlyCheckStart is true-ish and str starts with a space character or if opt_onlyCheckStart is false-ish and str only contains space characters. Otherwise false is returned.

Examples

console.log(YourJS.isSpace(''));                   // -> false
console.log(YourJS.isSpace(' '));                  // -> true
console.log(YourJS.isSpace('\xA0'));               // -> true
console.log(YourJS.isSpace(' \xA0'));              // -> true
console.log(YourJS.isSpace(' Cool'));              // -> false
console.log(YourJS.isSpace(' Cool', true));        // -> true
console.log(YourJS.isSpace('Hello world!'));       // -> false
console.log(YourJS.isSpace('Hello world!', true)); // -> false

isWhitespace(...) API Documentation

Description

Test for whitespace characters starting at the beginning of a string.

Parameters

  1. str {string}:
    The string to be tested.
  2. opt_onlyCheckStart {boolean}:
    Optional. Defaults to false. If true, only the beginning of the string is checked to see if it starts with a whitespace character. If false, all of the string is checked to see if it only contains whitespace characters.

Returns

Returns true if opt_onlyCheckStart is true-ish and str starts with a whitespace character or if opt_onlyCheckStart is false-ish and str only contains whitespace characters. Otherwise false is returned.

Examples

console.log(YourJS.isWhitespace(''));                   // -> false
console.log(YourJS.isWhitespace(' '));                  // -> true
console.log(YourJS.isWhitespace('\xA0'));               // -> false
console.log(YourJS.isWhitespace(' \t'));                // -> true
console.log(YourJS.isWhitespace('\tCool'));             // -> false
console.log(YourJS.isWhitespace('\tCool', true));       // -> true
console.log(YourJS.isWhitespace('Hello world!'));       // -> false
console.log(YourJS.isWhitespace('Hello world!', true)); // -> false