50

How do I detect if a string has any whitespace characters?

The below only detects actual space characters. I need to check for any kind of whitespace.

if(str.indexOf(' ') >= 0){
    console.log("contains spaces");
}
9
  • 4
    What you have will detect any spaces characters, not just between words. But do you want to include other types of white space? Commented Jul 12, 2013 at 13:59
  • 3
    console.log(' foo'.indexOf(' ') !== -1); logs true for me, as does console.log(' '.indexOf(' ') !== -1). console.log(''.indexOf(' ') !== -1) logs false, because an empty string doesn't contain spaces. Don't know what s holds for you, but indexOf should work Commented Jul 12, 2013 at 14:03
  • 6
    Only spaces between words? That's where spaces live. Commented Jul 12, 2013 at 14:03
  • 2
    Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. Commented Jul 12, 2013 at 14:10
  • 1
    I want to detect if the string contains ANY white spaces. Commented Jul 12, 2013 at 14:22

5 Answers 5

135

What you have will find a space anywhere in the string, not just between words.

If you want to find any kind of whitespace, you can use this, which uses a regular expression:

if (/\s/.test(str)) {
    // It has any kind of whitespace
}

\s means "any whitespace character" (spaces, tabs, vertical tabs, formfeeds, line breaks, etc.), and will find that character anywhere in the string.

According to MDN, \s is equivalent to: [ \f\n\r\t\v​\u00a0\u1680​\u180e\u2000​\u2001\u2002​\u2003\u2004​\u2005\u2006​\u2007\u2008​\u2009\u200a​\u2028\u2029​​\u202f\u205f​\u3000].


For some reason, I originally read your question as "How do I see if a string contains only spaces?" and so I answered with the below. But as @CrazyTrain points out, that's not what the question says. I'll leave it, though, just in case...

If you mean literally spaces, a regex can do it:

if (/^ *$/.test(str)) {
    // It has only spaces, or is empty
}

That says: Match the beginning of the string (^) followed by zero or more space characters followed by the end of the string ($). Change the * to a + if you don't want to match an empty string.

If you mean whitespace as a general concept:

if (/^\s*$/.test(str)) {
    // It has only whitespace
}

That uses \s (whitespace) rather than the space, but is otherwise the same. (And again, change * to + if you don't want to match an empty string.)

Sign up to request clarification or add additional context in comments.

7 Comments

This will also match empty string.
@HamZa: I was assuming that was desired.
T.J., that was really fast and straight forward!
@abhishah901: MDN is your friend (it's linked above). Or you can grab your safari hat and machete and delve into the specification, but it's a jungle in there, but this is one of the tamer parts of it.
@BKSpurgeon: It shouldn't, assuming you're editing a JavaScript file. That's a simple and valid statement.
|
4
function hasSpaces(str) {
  if (str.indexOf(' ') !== -1) {
    return true
  } else {
    return false
  }
}

1 Comment

there is many white space which is not equivalent with white space that you just made with your space bar. thus your code is not reliable.
1
var inValid = new RegExp('^[_A-z0-9]{1,}$');
var value = "test string";
var k = inValid.test(value);
alert(k);

1 Comment

Welcome to Stack Overflow. Answering questions is good but the purpose of this code is not clear. This answer would be much better if it inluded an explanation of what it does and how it answers the question. Please edit the answer.
1

A secondary option would be to check otherwise, with not space (\S), using an expression similar to:

^\S+$

Test

function has_any_spaces(regex, str) {
	if (regex.test(str) || str === '') {
		return false;
	}
	return true;
}

const expression = /^\S+$/g;
const string = 'foo  baz bar';

console.log(has_any_spaces(expression, string));

Here, we can for instance push strings without spaces into an array:

const regex = /^\S+$/gm;
const str = `
foo
foo baz
bar
foo baz bar
abc
abc abc
abc abc abc
`;
let m, arr = [];

while ((m = regex.exec(str)) !== null) {
	// This is necessary to avoid infinite loops with zero-width matches
	if (m.index === regex.lastIndex) {
		regex.lastIndex++;
	}

	// Here, we push those strings without spaces in an array
	m.forEach((match, groupIndex) => {
		arr.push(match);
	});
}
console.log(arr);


If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Comments

0
var string  = 'hello world';
var arr = string.split(''); // converted the string to an array and then checked: 
if(arr[i] === ' '){
   console.log(i);
}

I know regex can do the trick too!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.