4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【JavaScript】URL文字列が有効か判定する方法

Last updated at Posted at 2024-01-15

try...catchを使用する

URL()コンストラクターが与えられたURL文字列が有効でなければ例外をスローすることを利用して以下のように判定します。

function isValidURL(url) {
  try {
    new URL(url)
    return true
  } catch {
    return false
  }
}

URL.canParse()を使用する

URL.canParse()の引数にURL文字列を渡すことで有効か判定できます。

function isValidURL(url) {
  return URL.canParse(url)
}

参考

4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?