url match javascript in javascript

To match a URL in JavaScript, you can use a regular expression (regex) pattern to validate the URL string. Here is an example regex pattern that matches a URL in JavaScript:

index.tsx
const urlPattern = /^(?:\w+:)?\/\/([^\s.]+\.\S{2}|localhost[\:?\d]*)\S*$/;

const isUrlMatch = (url) => {
   return urlPattern.test(url);
};

// Example usage:
console.log(isUrlMatch("https://www.google.com")); //true
console.log(isUrlMatch("ftp://ftp.example.com/file.txt")); //true
console.log(isUrlMatch("invalid://url")); //false
334 chars
11 lines

This pattern allows for several different URL schemes (including both http and https), and will match URLs with or without query parameters. You can use this pattern to validate user input or check if a URL matches a certain pattern in your code.

gistlibby LogSnag