JavaScript check if string contains space or whitespace (indexOf, RegExp, trim)

Check if a string contains spaces in JavaScript: literal U+0020 vs Unicode whitespace, indexOf and includes, RegExp \s, trim for ends-only emptiness, and NBSP (U+00A0) pitfalls. Runnable Node snippets with short expected-output notes.

Published

Updated

Read time 4 min read

Reviewed byDeepak Prasad

JavaScript check if string contains space or whitespace (indexOf, RegExp, trim)

To javascript check if string contains space (the normal U+0020 character), use includes(" ") or indexOf(" ") >= 0. For any whitespace—tabs, newlines, many Unicode separators—use /\s/.test(str) when find space in string should mean “any whitespace class,” not only a normal space. For javascript check if string is empty or whitespace at the ends, str.trim() === "" is the usual pattern. Related: JavaScript string contains (substring checks) and check if string is number (after trimming input).

Tested on: Node.js v20.18.2. A short note after each snippet describes what you should see in the console.


Quick reference

Literal space checks use " " exactly; any ECMAScript whitespace uses /\s/; trim only answers “nothing meaningful at the edges.”

Goal Typical check
Literal space " " includes(" ") or indexOf(" ") >= 0
Tab / newline / Unicode whitespace /\s/.test(str)
Nothing left after trimming ends str.trim() === ""

indexOf — substring position (also works for a literal space)

String.prototype.indexOf returns the first index or -1. A second argument starts the search after a given index (useful for multiple occurrences, not only spaces in javascript).

javascript
const sentence =
  "The water levels across the earth, and that's due to an increase in rain centimetres and worsening climate change and maybe because due to ice melting to water too (who knows)";
const search = "water";
const indexOfSearchWord = sentence.indexOf(search);
const SecondIndexOfSearchWord = sentence.indexOf(search, indexOfSearchWord + 1);

console.log(`Index of the first ${search} is ${indexOfSearchWord}`);
console.log(`Index of the second ${search} is ${SecondIndexOfSearchWord}`);
Output

You should see two lines: Index of the first water is 4, then Index of the second water is 153.


Literal ASCII space only

For javascript check if string contains space as the single ASCII space character, compare against " " with indexOf or includes; other separators (tabs, NBSP) will not match.

javascript
const sentence = "Well, it is good";
const sentence1 = "Welcome";

function hasAsciiSpace(str) {
  return str.indexOf(" ") >= 0;
}

console.log(hasAsciiSpace(sentence));
console.log(hasAsciiSpace(sentence1));
Output

You should see two lines: true, then false.

Equivalent with includes:

javascript
console.log("a b".includes(" "));
Output

You should see one line: true.


Any whitespace — RegExp \s

For other methods for checking whitespace in javascript at the character level, /\s/ matches the ECMAScript whitespace class. Do not use a bare /s/ (that matches the letter “s”). The g flag is not required for RegExp.prototype.test.

javascript
const sentence = " Well, it is good";
const sentence1 = "Welcome";

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

console.log(hasWhitespace(sentence));
console.log(hasWhitespace(sentence1));
Output

You should see two lines: true, then false.

Leading space in the first string matches the tab-or-space class; Welcome has none.


NBSP vs literal space (Unicode pitfall)

A narrow no-break space (\u00A0) looks like a gap but is not the same code unit as " ":

javascript
const s = "a\u00A0b";
console.log(/\s/.test(s), s.includes(" "));
Output

You should see one line: true false.


Empty or whitespace-only — trim

For js check if string is empty or whitespace at the start and end only, trim strips those characters; internal spaces still leave a non-empty string after trim.

javascript
const isEmptyOrWhitespace = (str) => str.trim() === "";

console.log(isEmptyOrWhitespace("   "));
console.log(isEmptyOrWhitespace(" ok "));
Output

You should see two lines: true, then false.


Summary

Literal space vs Unicode whitespace vs ends-only emptiness are three different questions—pick the check that matches your product rule, and watch NBSP when copy-pasted text “looks” spaced.

  • Use includes(" ") or indexOf(" ") >= 0 for javascript check if string contains space as literal U+0020 only.
  • Use /\s/.test(str) when tabs, line breaks, or other ECMAScript whitespace must count toward find space in string.
  • Use str.trim() === "" for javascript check if string is empty or whitespace at the ends; combine with /\s/ if you must detect internal-only whitespace.
  • Remember NBSP and similar code units: visible gaps are not always " ".

References

MDN pages for indexOf, includes, trim, and regular expressions—core references for spaces in javascript and whitespace checks.


Frequently Asked Questions

1. How do I javascript check if string contains space only (U+0020)?

Use includes(' ') or indexOf(' ') >= 0. Both look for the literal ASCII space character, not tabs or non-breaking spaces.

2. How do I detect any whitespace including tabs or newlines?

Use a regular expression such as /\s/.test(str). That matches the ECMAScript whitespace class (space, tab, line terminators, and other Unicode whitespace), not just a normal space.

3. javascript check if string is empty or whitespace only?

Compare str.trim() === ''. trim removes leading and trailing whitespace per ECMAScript rules; if nothing remains, the string was empty or only whitespace at the ends. For internal-only spaces, combine with a /\s/ search.

4. indexOf vs includes for find space in string?

includes returns a boolean. indexOf returns the index or -1; use >= 0 for a boolean check. includes is often clearer for contains substring.

5. Why does includes(' ') return false when I see a gap between words?

The gap might be a narrow no-break space (U+00A0) or another Unicode separator. includes only matches the exact code unit you pass. Use /\s/ if you need any whitespace character.

6. Do I need the g flag on /\\s/g for test()?

No. test only needs the first match; /\s/.test(str) is enough. The g flag is mainly useful with exec in a loop or with replace.
Olorunfemi Akinlua

Boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs …