在JavaScript中过滤"仅限空白"的字符串

use*_*357 9 javascript string whitespace

我有一个文本框收集我的JS代码中的用户输入.我想过滤垃圾输入,就像只包含空格的字符串一样.

在C#中,我将使用以下代码:

if (inputString.Trim() == "") Console.WriteLine("white junk");
else Console.WriteLine("Valid input");
Run Code Online (Sandbox Code Playgroud)

你有任何推荐,如何在JavaScript中做同样的事情?

bob*_*nce 16

trim()字符串上的方法确实存在于ECMAScript第五版标准中,并且已由Mozilla(Firefox 3.5和相关浏览器)实现.

在其他浏览器赶上之前,您可以像这样修复它们:

if (!('trim' in String.prototype)) {
    String.prototype.trim= function() {
        return this.replace(/^\s+/, '').replace(/\s+$/, '');
    };
}
Run Code Online (Sandbox Code Playgroud)

然后:

if (inputString.trim()==='')
    alert('white junk');
Run Code Online (Sandbox Code Playgroud)


Mar*_*ers 12

使用正则表达式:

if (inputString.match(/^\s*$/)) { alert("not ok"); }
Run Code Online (Sandbox Code Playgroud)

甚至更容易:

if (inputString.match(/\S/)) { alert("ok"); }
Run Code Online (Sandbox Code Playgroud)

\ S表示'任何非空白字符'.