JS Regexp for shortname
I'm so bad at regexp expressions..
I've tried different things and nothing worked. :(
I'm just trying to verify that the shortname of someone could be added as url of my website like mysite.com/开发者_高级运维shortname
To do so, I absolutely need to be sure that it doesn't contain spaces, accent, special chars... juste [a-z] in fact.
I've tried this, but in vain:
function isShortValid(shortcode){
var pattern = new RegExp(/^([a-z]?$)/i);
return pattern.test(shortcode);
}
You don't need capture groups. Just use this regular expression to test your strings.
/^[a-z]+$/i
The bigger question here is of course:
Is it possible to input invalid short names into the system without getting a validation error on the input?
Because if it is possible, then you will have to resort to some other regular expression that will strip out invalid characters of your liking and create a correct short name when creating URLs. That URL parameter should of course be just a dummy segment (similar to stackoverflow). It's always wise to use direct user IDs that aren't changable and can't have invalid values because they're generated by the system.
These two links work the same:
https://stackoverflow.com/users/75642/robert-koritnik
https://stackoverflow.com/users/75642
The first one has the name included, but it's a dummy human friendly URL segment that can change at any time. ID on the other hand will always stay the same.
How to instantiate regular expressions
You can either instatiate a regular expression directly
var rx = /^[a-z]+$/i;
or by using a constructor
var rx = new RegExp("^[a-z]+$", "i");
Don't use slashes in constructor initialization unless they are part of the regular expression.
Try to change the regex to
var pattern = new RegExp('/^[a-z]+$/i');
This one worked perfectly. I added some numeric char too
function isShortValid(shortcode){
var pattern = new RegExp(/^[a-z_0-9]+$/i);
return pattern.test(shortcode);
}
EDIT: Thanks to all your comments and help, I used this one which is perfect! Thx again!
function isShortValid(shortcode){return /^\w+$/.test(shortcode);}
精彩评论