Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
过滤“;“仅限空白”;JavaScript中的字符串_Javascript_String_Whitespace - Fatal编程技术网

过滤“;“仅限空白”;JavaScript中的字符串

过滤“;“仅限空白”;JavaScript中的字符串,javascript,string,whitespace,Javascript,String,Whitespace,我有一个文本框,用于收集JS代码中的用户输入。我想过滤垃圾输入,比如只包含空格的字符串 在C#中,我将使用以下代码: if (inputString.Trim() == "") Console.WriteLine("white junk"); else Console.WriteLine("Valid input"); 您对如何在JavaScript中实现这一点有什么建议吗?使用正则表达式: if (inputString.match(/^\s*$/)) { alert("not ok");

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

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

if (inputString.Trim() == "") Console.WriteLine("white junk");
else Console.WriteLine("Valid input");

您对如何在JavaScript中实现这一点有什么建议吗?

使用正则表达式:

if (inputString.match(/^\s*$/)) { alert("not ok"); }
甚至更简单:

if (inputString.match(/\S/)) { alert("ok"); }
\S表示“任何非空白字符”

function trim (myString)
{
    return myString.replace(/^\s+/,'').replace(/\s+$/,'')
} 
像这样使用它:
如果(trim(myString)==”)

或者,
/^\s*$/.test(inputString)
字符串的
trim()方法确实存在于ECMAScript第五版标准中,并且已经由Mozilla(Firefox 3.5和相关浏览器)实现

在其他浏览器赶上之前,您可以按如下方式修复它们:

if (!('trim' in String.prototype)) {
    String.prototype.trim= function() {
        return this.replace(/^\s+/, '').replace(/\s+$/, '');
    };
}
然后:


是的,你是对的,我已经编辑了我的答案来删除它们。谢谢
if (inputString.trim()==='')
    alert('white junk');