0

replace domain name by js or jquery

my old domain is : www.a.com


new domain is : www.b.com


how to replace all a href links and canonical url with new domain for example

<a href="http://www.a.com/a.html">test</a>

replace with

<a href="http://www.b.com/a.html">test</a>

and

<link rel="canonical" href="http://a.com/a.html">

replace with

<link rel="canonical" href="http://b.com/a.html">
2
  • This seems a bit of a hacky solution. Why would you not update the source directly? Commented Sep 4, 2019 at 8:49
  • It could be part of a bookmarklet intended to replace website.com with archiveofwebsite.com (practically speaking, replace reddit.com with removeddit.com) Commented Feb 27, 2020 at 16:21

2 Answers 2

3

You can use URL api to find and replace hostname

const anchorTags = document.querySelectorAll('a')
anchorTags.forEach( anchor => {
  const href = anchor.getAttribute('href');
  const parsed = new URL(href)
  if (parsed.hostname === 'www.a.com') {
    parsed.hostname = 'www.b.com'
    anchor.setAttribute('href', parsed)
  }
})
console.log([...anchorTags.values()])
<a href="http://www.a.com/a.html">Link 1</a>
<a href="http://www.a.com/a.html">Link 2</a>
<a href="http://www.a.com/a.html">Link 3</a>
<a href="http://www.c.com/a.html">This link should not be touched</a>

Sign up to request clarification or add additional context in comments.

Comments

2

Not sure why you want to do this and not sure where your <link> elements are located But to change the href of the a elements you can use this

const a = document.querySelectorAll('a')
a.forEach((elem) => {
  const href = elem.getAttribute('href');
  if ( href.includes('www.a.com') ) {
   elem.setAttribute('href', href.replace('www.a.com','www.b.com'))
  }
})
console.log(a)
<a href="http://www.a.com/a.html">test</a>
<a href="http://www.a.com/a.html">test2</a>
<a href="http://www.a.com/a.html">test3</a>
<a href="http://www.c.com/a.html">dont change me</a>

2 Comments

well it's the same. Just select them in document.qureySelectorAll. Where are they located ?
@CodeManiac touche`

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.