Home > Web Front-end > JS Tutorial > How Can I Use Regular Expressions to Detect URLs, Including Naked URLs?

How Can I Use Regular Expressions to Detect URLs, Including Naked URLs?

DDD
Release: 2024-12-12 19:06:15
Original
123 people have browsed it

How Can I Use Regular Expressions to Detect URLs, Including Naked URLs?

Detecting URLs with Regular Expressions

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()@:%_\+.~#?&//=]*)
Copy after login

This enhanced expression includes the following features:

  • It ensures that URLs start with either "http://", "https://", or nothing.
  • It allows for subdomains by including "(www.)" as an optional prefix.
  • It supports domain names up to 256 characters in length and top-level domains up to 6 characters.

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()@:%_\+.~#?&//=]*)
Copy after login

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");
}
Copy after login

The above is the detailed content of How Can I Use Regular Expressions to Detect URLs, Including Naked URLs?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template