Your current code fails to match naked URLs, which lack the "http://" prefix. To address this, consider adopting a comprehensive regular expression:
https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\ ~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\ .~#?&//=]*)
This enhanced expression includes the following features:
For those who do not require the HTTP protocol in their matches, an alternative expression is available:
[-a-zA-Z0-9@:%._\ ~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\ .~#?&//=]*)
To demonstrate the functionality of these expressions, check out the online testing tools at http://regexr.com?37i6s (for the first expression) or http://regexr.com/3e6m0 (for the less restrictive expression).
Here's an example JavaScript implementation using the more comprehensive regular expression:
const expression = /[-a-zA-Z0-9@:%._\ ~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\ .~#?&//=]*)/gi; const regex = new RegExp(expression); const t = 'www.google.com'; if (t.match(regex)) { alert("Successful match"); } else { alert("No match"); }
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3