Abs
Abs

Reputation: 57916

Check if a string has white space

I'm trying to check if a string has white space. I found this function but it doesn't seem to be working:

function hasWhiteSpace(s) 
{
    var reWhiteSpace = new RegExp("/^\s+$/");

    // Check for white space
    if (reWhiteSpace.test(s)) {
        //alert("Please Check Your Fields For Spaces");
        return false;
    }

    return true;
}

By the way, I added quotes to RegExp.

Is there something wrong? Is there anything better that I can use? Hopefully JQuery.

Upvotes: 158

Views: 434554

Answers (11)

Ruben Verster
Ruben Verster

Reputation: 362

const checkEmpty = (title: string) => {
    let testString = title.replaceAll(" ", "");

    if (testString.length === 0) {
      return true;
    }
    return false;
  };

This is what I'm using to check if the input contains just whitespaces You can also just use the '.includes' operator to check if there are whitespaces included in the string :)

Upvotes: 1

Enrique Palacio
Enrique Palacio

Reputation: 1761

If you are using ECMAScript6 (ES6) or newer, the easiest method that will do the magic is show below

// looking just for spaces   
function hasWhiteSpace(s) {
  return s.includes(' ');
}

Above function have a couple of limitations,

  • It just match the white space but no other possible whitespace characters as tab or line break.
  • It doesn't support Regex.

If We need to use a Regex to match all possible whitespace characters, We can use search option that is available since ECMAScript1 (ES1):

// looking for spaces, tabs, line breakers, etc. 
// live example: https://www.w3schools.com/jsref/jsref_regexp_whitespace.asp
function hasWhiteSpace(s) {
  return s.search(/\s/);
}

// looking just for spaces, equivalent to includes option
function hasWhiteSpace(s) {
  return s.search(/ /);
}

This will also check for other white space characters like Tab.

Upvotes: 8

PaulG
PaulG

Reputation: 3481

One simple approach you could take is to compare the length of the original string with that of the string to have whitespaces replaced with nothing. For example:

const hasWhiteSpaces = (text: string) => text.length === text.replace(" ", "").length

Upvotes: 1

snnsnn
snnsnn

Reputation: 13600

The test method is the best way to go. The character class \s checks for any whitespace character including space, tab, carriage return and form feed.

The global flag is not necessary since we are looking for a single match. Regex literals run faster than their constructor equivalents because they are better optimized by the runtime.

function hasWhiteSpace(s) {
  return (/\s/).test(s);
}

console.log(hasWhiteSpace("Hello World!"));
console.log(hasWhiteSpace("HelloWorld!"));

console.time('hasWhiteSpace');
for (let i = 0; i < 1_000_000; i++) {
  hasWhiteSpace("Some text here");
}
console.timeEnd('hasWhiteSpace');

If you are working with certain whitespace characters only, you can take advantage of array methods like some which returns on first successful match but they will be slower than the regex's test method:

// Use includes method on string
function hasWhiteSpace(s) {
  const whitespaceChars = [' ', '\t', '\n'];
  return whitespaceChars.some(char => s.includes(char));
}

console.log(hasWhiteSpace("Hello World!"));
console.log(hasWhiteSpace("HelloWorld!"));

console.time('hasWhiteSpace');
for (let i = 0; i < 1_000_000; i++) {
  hasWhiteSpace("Some text here");
}
console.timeEnd('hasWhiteSpace');

As you see in the performance benchmarks, the test method is slightly faster than some method which won't be noticeable anyway.

Upvotes: 11

Arun Kenjila
Arun Kenjila

Reputation: 169

I think we can use includes()

message :string = "Hello world";
message2 : string = "Helloworld";

message.includes(' '); // true
message2.inlcudes(' ')// false

Upvotes: 2

leonheess
leonheess

Reputation: 21351

function hasWhiteSpace(s) {
  return s.includes(' ')
}

Upvotes: 1

HoldOffHunger
HoldOffHunger

Reputation: 20851

A few others have posted answers. There are some obvious problems, like it returns false when the Regex passes, and the ^ and $ operators indicate start/end, whereas the question is looking for has (any) whitespace, and not: only contains whitespace (which the regex is checking).

Besides that, the issue is just a typo.

Change this...

var reWhiteSpace = new RegExp("/^\s+$/");

To this...

var reWhiteSpace = new RegExp("\\s+");

When using a regex within RegExp(), you must do the two following things...

  • Omit starting and ending / brackets.
  • Double-escape all sequences code, i.e., \\s in place of \s, etc.

Full working demo from source code....

$(document).ready(function(e) { function hasWhiteSpace(s) {
        var reWhiteSpace = new RegExp("\\s+");
    
        // Check for white space
        if (reWhiteSpace.test(s)) {
            //alert("Please Check Your Fields For Spaces");
            return 'true';
        }
    
        return 'false';
    }
  
  $('#whitespace1').html(hasWhiteSpace(' '));
  $('#whitespace2').html(hasWhiteSpace('123'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
" ": <span id="whitespace1"></span><br>
"123": <span id="whitespace2"></span>

Upvotes: 4

JesterXL
JesterXL

Reputation: 308

This function checks for other types of whitespace, not just space (tab, carriage return, etc.)

import some from 'lodash/fp/some'
const whitespaceCharacters = [' ', '  ',
  '\b', '\t', '\n', '\v', '\f', '\r', `\"`, `\'`, `\\`,
  '\u0008', '\u0009', '\u000A', '\u000B', '\u000C',
'\u000D', '\u0020','\u0022', '\u0027', '\u005C',
'\u00A0', '\u2028', '\u2029', '\uFEFF']
const hasWhitespace = char => some(
  w => char.indexOf(w) > -1,
  whitespaceCharacters
)

console.log(hasWhitespace('a')); // a, false
console.log(hasWhitespace(' ')); // space, true
console.log(hasWhitespace(' ')); // tab, true
console.log(hasWhitespace('\r')); // carriage return, true

If you don't want to use Lodash, then here is a simple some implementation with 2 s:

const ssome = (predicate, list) =>
{
  const len = list.length;
  for(const i = 0; i<len; i++)
  {
    if(predicate(list[i]) === true) {
      return true;
    }
  }
  return false;
};

Then just replace some with ssome.

const hasWhitespace = char => some(
  w => char.indexOf(w) > -1,
  whitespaceCharacters
)

For those in Node, use:

const { some } = require('lodash/fp');

Upvotes: 2

CyborgHead
CyborgHead

Reputation: 11

Here is my suggested validation:

var isValid = false;

// Check whether this entered value is numeric.
function checkNumeric() {
    var numericVal = document.getElementById("txt_numeric").value;

    if(isNaN(numericVal) || numericVal == "" || numericVal == null || numericVal.indexOf(' ') >= 0) {
        alert("Please, enter a numeric value!");
        isValid = false;
    } else {
        isValid = true;
    }
}

Upvotes: 0

Ian Clelland
Ian Clelland

Reputation: 44122

Your regex won't match anything, as it is. You definitely need to remove the quotes -- the "/" characters are sufficient.

/^\s+$/ is checking whether the string is ALL whitespace:

  • ^ matches the start of the string.
  • \s+ means at least 1, possibly more, spaces.
  • $ matches the end of the string.

Try replacing the regex with /\s/ (and no quotes)

Upvotes: 37

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 827218

You can simply use the indexOf method on the input string:

function hasWhiteSpace(s) {
  return s.indexOf(' ') >= 0;
}

Or you can use the test method, on a simple RegEx:

function hasWhiteSpace(s) {
  return /\s/g.test(s);
}

This will also check for other white space characters like Tab.

Upvotes: 347

Related Questions