Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript regex issue for folders names

I’m trying to create a regex to allow alphanumeric strings with hyphens, underscores and spaces allowed. The string must start with a number or a letter and be a maximum total of 20.

Here is my code:

    var regex = /^[a-zA-Z0-9]+([a-zA-Z0-9_ -]){0,20}$/;
    var newName = "12345678901234567890233_pm";
    if (regex.test(newName)) {
        console.log('yes');
    }else{
        console.log('no');
    } 

My code always returns yes. Is my regex wrong please?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks.

>Solution :

Your use of the + quantifier in the first character class does not do what you seem to think it does – it’s actually not at all necessary in this context. Additionally, since the first character class accounts for 1 of the 20 maximum characters, reduce the maximum quantifier in the second character class to 19:

    var regex = /^[a-zA-Z0-9][a-zA-Z0-9_ -]{0,19}$/;
    var newName = "12345678901234567890233_pm";
    if (regex.test(newName)) {
        console.log('yes');
    }else{
        console.log('no');
    } 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading