过滤“仅空白” JavaScript中的字符串 [英] Filtering "whitespace-only" strings in JavaScript

查看:70
本文介绍了过滤“仅空白” JavaScript中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a textbox collecting user input in my JS code. I would like to filter junk input, like strings that contain whitespaces only.

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

In C#, I would use the following code:

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

您有什么建议,如何在JavaScript中做同样的事情?

Do you have any recommendation, how to do the same in JavaScript?

推荐答案

字符串上的 trim()方法确实存在于ECMAScript第五版标准中并已实施通过Mozilla(Firefox 3.5和相关浏览器)。

The trim() method on strings does exist in the ECMAScript Fifth Edition standard and has been implemented by Mozilla (Firefox 3.5 and related browsers).

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

Until the other browsers catch up, you can fix them up like this:

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

然后:

if (inputString.trim()==='')
    alert('white junk');

这篇关于过滤“仅空白” JavaScript中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆