We need to determine whether the user input is all spaces, you can use the following methods: Method one: Using Trim ()
/* 使用String.trim()函数,来判断字符串是否全为空*/function kongge1(test) { let str = test.trim(); if (str.length == 0) { console.log(‘字符串全是空格‘); } else { console.log(‘输入的字符串为:‘ + test); }}
If trim () does not exist, you can execute the following code before all code/ * Add method trim to string prototype chain Object */
if (! String.prototype.trim) {
String.prototype.trim = function () {
Return This.replace (/^[\s\ufeff\xa0]+|[ \s\ufeff\xa0]+$/g, ");
};
}For example:/* Use the String.Trim () function to determine whether the string is all empty */function kongge1 (test) {/* Adds a method trim */if (!) to the string prototype chain object. String.prototype.trim) {String.prototype.trim = function () {return this.replace (/^[\s\ufeff\xa0]+|[ \s\ufeff\xa0]+$/g, "); }; } Let str = Test.trim (); if (Str.length = = 0) {console.log (' string is all spaces '); } else {console.log (' Input string: ' + Test '); }}
Method Two: Use regular expressions
/* 使用正则表达式来判断字符串是否全为空 */function kongge2(test) { if(test.match(/^\s+$/)){ console.log("all space or \\n"); } if(test.match(/^[ ]+$/)){ console.log("all space") } if(test.match(/^[ ]*$/)){ console.log("all space or empty") } if(test.match(/^\s*$/)){ console.log("all space or \\n or empty") } else { console.log(‘输入的字符串为:‘ + test); }}
Case:
<! DOCTYPE html>
JS to determine if the string is all empty (using trim function/Regular expression)