Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step
https://juejin.cn/column/7244788137410560055
2.03k stars 235 forks source link

正则表达式匹配URL #478

Open Pcjmy opened 1 year ago

kangkang123269 commented 1 year ago
const isValidUrl = (url) => {
  const urlRegex = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:((?:(?=[^.-])[\w-]+\.)*[\w-]{2,}\.?(?=[^.-])(?:\.[a-z]{2,})?))(:\d{1,5})?(\/\S*)?$/i;
  return urlRegex.test(url);
}

console.log(isValidUrl('https://www.example.com/path/to/resource')); // true
console.log(isValidUrl('ftp://example.com/file.txt')); // true
console.log(isValidUrl('http://localhost:8080')); // true
console.log(isValidUrl('invalid url')); // false