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

What is the difference between using regex expressions when used by direct html vs when used in JavaScript?

I have an input form validator like this:

<input pattern="[a-zA-Z]{2,}" .../>

Which works fine to validate html input.

However when I try to use the same in JavaScript:

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

const regExp = new RegExp("[a-zA-Z]{2,}");

this regex behaves unexpectedly as in html:

enter image description here

but in javascript:
enter image description here

Can someone tell me what am I missing? Ideally I would want to pass regexString in a utility function rather than using /.

>Solution :

You are missing the start and end of line characters. The following should work in JS as the pattern property of the input does.

const regExp = new RegExp("^[a-zA-Z]{2,}$");

The pattern property of input has the start and end characters intrinsically included, since the input is checked as a whole, while in JS you might use a regular expression to test a whole text, where the pattern could match multiple times, if you are not using the start and end of line characters.

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