2

I have dynamically generated buttons with url using data attributes

<button class="btn-Add" type="button" data-add-url="/AddProductToCart?mobileNo=__param__&amp;
productId=2051&amp;quantity=1">Add to Cart</button>

I have the following code:

$(document).ready(function () {
    var mobileNo = 0;
    $(".btn-Add").click(function () {
        mobileNo = $(this).parent('.pro-Group').find('input[type=text]').val();
        var postURL = $(this).data('add-url');
        postURL.replace('__param__', mobileNo);
        alert(postURL); // i can still see __param__ , its not replaced
    });
});

Why query string value is not replaced after using replace method ?

2
  • 3
    postURL = postURL.replace('__param__', mobileNo); ?? Commented Apr 27, 2017 at 12:14
  • @Sysix , Thanks for the comment and finding my mistake, it works now. Commented Apr 27, 2017 at 12:23

1 Answer 1

3

Javascript Strings are immutable. So once their value got assigned they can't changes their values.

So you have to reassign them with new changes or have to receive them in new variables. Generally we reassign as there is no need of new variable to be introduced unless you need old value .

  postURL = postURL.replace('__param__', mobileNo);
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the explanation and finding my mistake, it works now. Initially I thought it would work without reassigning them.
@stom You are correct in case mutable objects. You are welcome.
@ANS for the description +1

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.