Regex match common websites URL

Viewed 62

I have a component that I want to use for forms and it's for websites. However, there are multiple possible patterns:

Question:

How can I set the pattern for the input to account for these possible URL patterns?

Component.tsx:

<Form.Control
  type="url"
  placeholder="Website"
  pattern="https?://.*"
  onChange={(event: React.ChangeEvent<HTMLInputElement>) => setValue((event.target.value).toLowerCase())}
  maxLength={100}
/>
1 Answers

For some basic websites URL matching you could:

^(https?:\/\/|www\.)\S+\.\w+$

Which will match:

https://www.website.com  
http://www.website.com  
http://website.com  
http://www.com           (yep, that's a valid website)
www.website.com  

but not

https://website
http://.com
website.com
www.com
website

"basic" because of the \S+ part just ensures the Domain has no whitespace characters.

Regex101.com example

Related