Jump to content

How to replace text


newcoder1010

Recommended Posts

Hello, 

<div class="field--item"><a href="http://example.com" target="_blank">http://example.com</a></div>

I will have many links like that. Is there way I can replace the link with "visit website"?

So instead of displaying http://example.com as a link, I like to display "visit website" as a link which will redirect to the website. 

Thanks!

Link to comment
Share on other sites

It looks like the links are generated using a content management system like Drupal, so I don't think they have a way to change the HTML directly.

Ideally, it would be best alter the content management system to generate the links with the correct text. How this is done depends on what CMS you're using and how you're using it.

If that's not an option, then you could use Javascript to loop through links and edit the text for each one of them. You will have to specify what text you want for each link, which I've done with an object.

function editLinks() {
  
  // THe left indicates the current value and the right indicates what we want to change it to
  var replacements = {
    "http://example.com" : "Visit Website 1",
    "https://example.com" : "Visit Website 1",
    "http://example2.com" : "Visit Website 2",
    "https://example2.com" : "Visit Website 2"
  };
  
  // Loop through every link on th page.
  // If you have more information, you can select a smaller range of links to test.
  var links = document.getElementsByTagName("a");
  for(let i = 0; i < links.length; i++) {
    let link = links[i];
    // If a replacement was found then change the link text
    if(replacements[link.text]) {
      link.text = replacements[link.text];
    }
  }
}

// The above function should start running when the page has finished loading.
window.addEventListener("DOMContentLoaded", editLinks);

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...