Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check Space in String

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;
  }
like image 909
Azam Alvi Avatar asked Sep 16 '26 09:09

Azam Alvi


2 Answers

Just use .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)
};
like image 143
Blender Avatar answered Sep 18 '26 21:09

Blender


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

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

See the code in action in this jsFiddle.

like image 44
doublesharp Avatar answered Sep 18 '26 21:09

doublesharp