Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string has white space

People also ask

How do you check if a string contains a space in C++?

The isspace() function in C++ checks if the given character is a whitespace character or not.

Is an empty string white space?

First you should know the difference between empty string and a white space. The length of a white ' ' space is 1 . An empty string '' will have a length zero.


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.


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)


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.


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>

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');

I think we can use includes()

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

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

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