Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether the first character is a space

How can I check if the first character of the input field is an empty space or not with jQuery? I would need to check so that users can't enter a username like " rreea". Empty spaces after the first character are allowed. For example, "his name" is okay, but " his name" or " hisname" are not accepted.

like image 366
user1069269 Avatar asked Sep 06 '25 17:09

user1069269


2 Answers

In spite of checking just add string trimming using $.trim method. It removes all spaces from left and right edges of the string.

var value = $.trim($("input").val());

Otherwise, you can use

$("input").val().substring(0, 1)

to get the first character safely.

like image 196
VisioN Avatar answered Sep 09 '25 22:09

VisioN


You can use myString.substring(0,1) or myString[0] to get the first character.

You can trim the input; this doesn't check whether or not it starts with a space, it makes such a check redundant and gives you usable input regardless of whether or not the original string had an initial space.

You could also match the string for /^\s/ which means an initial whitespace, or /^\s+/ meaning any number of initial whitespace.

like image 24
David Hedlund Avatar answered Sep 09 '25 22:09

David Hedlund