Home > Web Front-end > JS Tutorial > How Can I Efficiently Match URLs Using Regular Expressions?

How Can I Efficiently Match URLs Using Regular Expressions?

Patricia Arquette
Release: 2024-12-19 10:50:09
Original
623 people have browsed it

How Can I Efficiently Match URLs Using Regular Expressions?

How to Efficiently Match URLs Using Regular Expressions

Regular expressions provide a powerful way to validate and parse complex strings, including URLs. To ensure accurate URL detection in your input box, consider using these optimized regular expressions:

Regex for URLs with HTTP/HTTPS Protocol:

https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)
Copy after login

Regex for URLs without Protocol Requirement:

[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)
Copy after login

JavaScript Implementation Example:

const regex = new RegExp(expression);
const t = 'www.google.com';

if (t.match(regex)) {
  alert("Successful match");
} else {
  alert("No match");
}
Copy after login

These regular expressions will accurately detect URLs, regardless of whether they start with "http" or "https". They are less restrictive than your current regex, allowing you to parse URLs in various formats without issues. By adhering to these regex patterns, you can enhance the efficiency and accuracy of your URL parsing functionality.

The above is the detailed content of How Can I Efficiently Match URLs Using Regular Expressions?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template