Devmix
Devmix

Reputation: 1868

How to check if string contains ONLY one space?

I know that if I want to check for more than 1 space I can do this:

  if (str.match(".*  .*")) { 
       console.log('String contains more than 1 space');
   }

But how to check if string has ONLY ONE string like: "t " or " t"

Upvotes: 1

Views: 935

Answers (2)

Aurel Bílý
Aurel Bílý

Reputation: 7983

A possible non-RE solution (perhaps faster) would be to use split, like so:

let spaces = str.split(" ").length - 1;
if (spaces > 1) { 
  console.log('String contains more than 1 space');
}

Upvotes: 1

Pointy
Pointy

Reputation: 413826

You can match strings that have some number of non-spaces, then a single space, and then more non-spaces to the end of the string:

var oneSpace = /^[^ ]* [^ ]*$/;

The ^ and $ anchors are important because the pattern only matches the complete string and not just parts.

Upvotes: 2

Related Questions