jQuery 检查字符串中的空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15858829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:54:29  来源:igfitidea点击:

Check Space in String

javascriptjquery

提问by Azam Alvi

I want to check that if my username contains space so then it alert so i do this it work but one problem i am facing is that if i give space in start then it does not alert.I search it but can't find solution, my code is this

我想检查我的用户名是否包含空格,然后它会发出警报,所以我这样做它可以工作,但我面临的一个问题是,如果我在开始时提供空间,则它不会发出警报。我搜索它但找不到解决方案,我的代码是这样的

var username    =   $.trim($('#r_uname').val());
var space = " ";
  var check = function(string){
   for(i = 0; i < space.length;i++){
     if(string.indexOf(space[i]) > -1){
         return true
      }
   }
   return false;
  }

  if(check(username) == true)
  {
     alert('Username contains illegal characters or Space!');
     return false;
  }

回答by Blender

Just use .indexOf():

只需使用.indexOf()

var check = function(string) {
    return string.indexOf(' ') === -1;
};

You could also use regex to restrict the username to a particular format:

您还可以使用正则表达式将用户名限制为特定格式:

var check = function(string) {
    return /^[a-z0-9_]+$/i.test(string)
};

回答by doublesharp

You should use a regular expression to check for a whitespace character with \s:

您应该使用正则表达式来检查空格字符\s

if (username.match(/\s/g)){
    alert('There is a space!');
}

See the code in action in this jsFiddle.

请参阅此jsFiddle中的操作代码。

回答by Javid Dadashkarimi

why you don't use something like this?

你为什么不使用这样的东西?

if(string.indexOf(space) > -1){
     return true
  }