Search code examples
jquerystrip

How can I get the href value from a link to use as value?


I have following setup:

<div class="map-container">
  <div class="map-pointer">
    <a href="https://my-link-1.com"></a>
  </div>
  <div class="map-pointer">
    <a href="https://my-link-2.com"></a>
  </div>
  <div class="map-pointer">
    <a href="https://my-link-3.com"></a>
  </div>
  ... 15 .map-pointer div's in total
</div>

What I want to do is that the content of the a-element will be automatically filled in with the value of the href. Stripped from the https://, the '-' and .com.

So my links will eventually look like this:

<a href="https://my-link-1.com">my link 1</a>
<a href="https://my-link-2.com">my link 2</a>
...

Is this possible with jQuery? I'm not sure where to begin. I know that I first have to store the href attribute in a variable. But how can I do that for all the different links?


Solution

  • Can do something like this:

    $("a").each(function() {
         var linkName;
         linkName = this.href.replace("https://", "");
         linkName = linkName.replace(/-/g," ");
         linkName = linkName.replace(".com/", "");
         this.innerHTML = linkName;
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="map-container">
      <div class="map-pointer">
        <a href="https://my-link-1.com"></a>
      </div>
      <div class="map-pointer">
        <a href="https://my-link-2.com"></a>
      </div>
      <div class="map-pointer">
        <a href="https://my-link-3.com"></a>
      </div>
    </div>