Reputation: 1868
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
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
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