简体   繁体   中英

How to change all external links with Javascript?

I want to replace all my external links using Javascript.. I just want to add " http://example.com/go= " before every external links... How will I do that? Please help..

You can iterate document.links HTMLCollection and set .href property to the required string if the current .href does not include document.domain

Array.from(document.links)
.forEach(link => 
  link.href = new RegExp(document.domain).test(link.href)
              ? link.href : "http://example.com/go=")

The following snippet should work. It iterates over all <a> elements and checks if the href contains the current domain (I test it using an RegExp, but there's also solutions thinkable as well). If not, the prefix is added.

 const originReg = new RegExp(location.hostname, 'i'); document.querySelectorAll('a').forEach(a => { if (originReg.test(a.href)) return /* internal link */; a.href = `http://example.com/go?url=${encodeURI(a.href)}`; }); 
 <a href="/bar">Bar</a> <a href="baz">Baz</a> <a href="http://example.com/foo">Foo</a> 

document.querySelectorAll('a').forEach((anchor) => {

  // make sure we return the relative path, not the absolute
  // getAttribute(), not .href
  const href = anchor.getAttribute('href');
  const str = 'http://example.com/go=';

  // if the link is an external link, update
  // the href attribute
  /:\/\//.test(href) && anchor.setAttribute('href', str + href);
});

Example

This will only target external links.

document.querySelectorAll('a').forEach((anchor) => {

  // make sure we return the relative path, not the absolute
  const target = anchor.getAttribute('target');

   If ( target === '_blank' ){
        const href = anchor.getAttribute('href');
        const str = 'http://example.com/go=';

       anchor.setAttribute('href', str + href);
  }
});

// most of this was an edit to @Andy code. I did not want to make major changes to what was there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM