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
Patricia ArquetteOriginal
2024-12-19 10:50:09624browse

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

Regex for URLs without Protocol Requirement:

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

JavaScript Implementation Example:

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

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

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!

Statement:
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