LoginSignup
1
2

More than 5 years have passed since last update.

リンク先が現在のページかを確認する方法

Last updated at Posted at 2017-03-24
const matchLocation = (href) => {
  if(typeof href !== 'string') {
    throw new TypeError('Not string.');
  }

  const { hostname, port, pathname } = location;
  const _hostname = hostname.replace(/([\/\.\*\(\)])/g, '\\$1');
  const _pathname = pathname.replace(/\//g, '\\\/');

  const _r = new RegExp(
    `^(http|https):\\\/\\\/${ _hostname }(:(${ port })?)?${ _pathname }(\\\?.+)?(#.*)?$`
  );

  return href.match(_r);
};

const el = document.getElementsByTagName('a')[0];

matchLocation(el.href);

パラメータとハッシュは無視するようにしています。

1
2
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
1
2