如何检测用户输入是否仅为空白字符?现有方案误判问题求最优解
Got it, let's sort out this issue quickly! The problem with your current code is that /\s/g.test(s) checks if there's any whitespace character in the input—so even valid strings with spaces like 'hi there' or 'john doe' will trigger the error, which isn't what you want.
The Solution: Match Entirely Whitespace Strings
We need a regex that only returns true when the entire input consists of nothing but whitespace characters (and optionally handles empty strings if needed). Here are two tailored options:
For inputs with one or more whitespace characters (e.g., ' ', ' ', '\t'):
Use^(start of string) and$(end of string) to anchor the match, with\s+to match one or more whitespace characters.function whitespaceDetect(s) { return /^\s+$/.test(s); } const inputValue = document.getElementById("name").value; if (whitespaceDetect(inputValue)) { alert('error!'); }For empty strings OR inputs with whitespace (if you want to block blank submissions entirely):
Swap+with*to match zero or more whitespace characters (this includes empty input):function whitespaceDetect(s) { return /^\s*$/.test(s); }
Why This Works
^ensures we start checking from the very beginning of the string.$ensures we stop at the very end of the string.\smatches any whitespace character (spaces, tabs, newlines, etc.).+requires at least one whitespace character, while*allows zero (covering empty inputs).
This way, valid strings with spaces mixed with non-whitespace characters will not trigger the error, exactly as you need.
内容的提问来源于stack exchange,提问作者pixie123

