检查字符串是否有空格 [英] Check if a string has white space

查看:126
本文介绍了检查字符串是否有空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查字符串是否有空格。我找到了这个功能,但它似乎没有工作:

I'm trying to check if a string has white space. I found this function but it doesn't seem to be working:

function hasWhiteSpace(s) 
{
    var reWhiteSpace = new RegExp("/^\s+$/");

    // Check for white space
    if (reWhiteSpace.test(s)) {
        //alert("Please Check Your Fields For Spaces");
        return false;
    }

    return true;
}

顺便说一句,我在 RegExp <中添加了引号/ code>。

By the way, I added quotes to RegExp.

有什么问题吗?有什么更好的我可以用吗?希望JQuery。

Is there something wrong? Is there anything better that I can use? Hopefully JQuery.

推荐答案

你可以简单地使用 indexOf 方法:

You can simply use the indexOf method on the input string:

function hasWhiteSpace(s) {
  return s.indexOf(' ') >= 0;
}

或者您可以在简单的RegEx上使用测试方法:

Or you can use the test method, on a simple RegEx:

function hasWhiteSpace(s) {
  return /\s/g.test(s);
}

这也会检查Tab等其他空格字符。

This will also check for other white space characters like Tab.

这篇关于检查字符串是否有空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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