How to check if a user input text is all white space characters (space, tab, enter etc) in client side?
If you want to see if a file contains all white space or is empty, I would recommend testing the inversion and inverting the result. That way you don't need to worry about special cases around empty string.
all whitespace is the same as no non-whitespace so:
function isWhitespaceOrEmpty(text) {
return !/[^\s]/.test(text);
}
If you don't want empty strings you can modify it slightly:
function isWhitespaceNotEmpty(text) {
return text.length > 0 && !/[^\s]/.test(text);
}
// ^ start string
// || \s+ white space one or more times
// || || $ = end string
// || || ||
// \/ \/ \/
const isAllWhiteSpace = /^\s+$/.test(myvalue)
Like this...
function isEmpty(str) {
return str.replace(/^\s+|\s+$/g, '').length == 0;
}
This will also work:
var text = " ";
text.trim().length == 0; //true
yo, we can check simply bt trim, as javascript is tagged in question,
console.log(' '.trim() === '')//check for all empty spaces
console.log(' '.trim() === '')//check for all empty tabs
console.log('\n \n'.trim() === '')//check for all empty enter(empty new line)
console.log(' \n'.trim() === '')//check for all spaces, tabs and new line
To find whitespace generated by JavaScript and between elements use:
var trimmed = $.trim( $('p').text() );
if ( trimmed === '' ){
//function...
}