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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With