Charly
Charly

Reputation: 189

Cannot get rid of backslash with jQuery's replace function

I'm having issues getting rid of the backlash symbol. I'm trying to convert a url like this: /apple to /fruit#apple

Thanks!

$(document).ready(function () {

    $('.product').each(function () {

        var productLink = $(this).find('a').attr('href');

        productLink.replace(/\//, "");

        productLink = "/fruits#" + $(this);


    });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="product">
        <h2>Fruit 1</h2>
        <a href="/apple">Learn More</a>
    </div>
    <div class="product">
        <h2>Fruit 2</h2>
        <a href="/orange">Learn More</a>
    </div>

Upvotes: 0

Views: 41

Answers (1)

Guerric P
Guerric P

Reputation: 31815

You were just missing the "put the result as attribute" part:

$(document).ready(function () {

    $('.product').each(function () {

        var productLink = $(this).find('a').attr('href').replace(/\//, "");

        $(this).find('a').attr('href', "/fruits#" + productLink );


    });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="product">
        <h2>Fruit 1</h2>
        <a href="/apple">Learn More</a>
    </div>
    <div class="product">
        <h2>Fruit 2</h2>
        <a href="/orange">Learn More</a>
    </div>

Upvotes: 1

Related Questions