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

how to allow only 1 forward slash in regex expression

I have regex expression to check alpha numeric inputs max 16 which is following

^[a-zA-Z0-9]{0,16}$

how i can modify this to check it should have only 1 forward slash. like

aas/as12

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

12/saad

>Solution :

You can use:

^(?!.{17})[a-z\d]+\/[a-z\d]+$

See an online demo


  • ^ – Start-line anchor;
  • (?!.{17}) – Negative lookahead to prevent 17 characters (other than newline). This can be more precise and you may want to change into 18 depending if you count the forward slash on top of the 16 alphanumeric characters.
  • [a-z\d]+\/[a-z\d]+ – 1+ Alphanumeric chars, a single literal forward slash and again 1+ alphanumeric chars.
  • $ – End-line anchor.

Note that I used case-insensitive matches, meaning your JS-pattern would look like:

/^(?!.{17})[a-z\d]+\/[a-z\d]+$/gi
const regex = /^(?!.{17})[a-z\d]+\/[a-z\d]+$/i;
[
  "aas/as12",
  "12/saad",
  "/"
].forEach(s =>
  console.log(`${s} --> ${regex.test(s)}`)
)
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