Char
Char

Reputation: 2133

Test for not all spaces

How do you say it in a condition that name is not equal to spaces? I have this

name != null && name !== ' '

But it still continues to search with multiple spaces. It only stops searching with one space. How about if there are a lot of space?

Upvotes: 0

Views: 125

Answers (2)

Brian Putt
Brian Putt

Reputation: 1348

I'd recommend using the trim function. It'll remove all white space and therefore match.

name !== null && name.trim() !== ''

enter image description here

Upvotes: 2

user663031
user663031

Reputation:

Test for the presence of any non whitespace character:

/\S/.test(string)

function notAllSpaces(str) { return str && /\S/.test(str); }

const data= ['', ' ', '  ', ' A '];

data.forEach(str => console.log("'" + str + "'", 
  notAllSpaces(str) ? "not all spaces" : "all spaces"));

To test for the presence of any character which is not a space, including whitespace characters like tab and newline, replace the \S with [^ ].

Upvotes: 0

Related Questions