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.
A secondary option would be to check otherwise, with not space (\S), using an expression similar to:
^\S+$
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.
jex.im visualizes regular expressions: