1

I have a link like following

<a id="dynamicLink" href="http://www.w3schools.com?userName=test">Visit W3Schools</a>

I would like to change the value of userName from test to test1.

How to do that using javascript?

could someone help me on this?

1
  • 1
    May i know the reason why i got down vote ? Commented Jul 14, 2015 at 11:41

2 Answers 2

3

I suggest using a library to work with URIs. It will provide some consistency. Here is an example using URI.js:

// Get our <a> element
var l = document.getElementById('dynamicLink');

// Use URI.js to work with the URI
// http://medialize.github.io/URI.js/
var uri = URI(l.href);

// Get the query string as an object
var qs = uri.query(true);

// Change our value
qs.userName = 'test1'

// Update the URI object
uri.query(qs);

// Set our new HREF on the <a> element
l.href = uri;
<script src="https://cdnjs.cloudflare.com/ajax/libs/URI.js/1.15.2/URI.min.js"></script>

<a id="dynamicLink" href="http://www.w3schools.com?userName=test&someOtherKey=val">Visit W3Schools</a>

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

4 Comments

Jon Surrell this is replacing the text but removes other parameter also if i pass the comma separated value then it creates multiple parameter for each value. Please suggest as how to proceed further.
@Tony I've changed the example to account for this. You can also refer to the URI.js docs
Thank you Jon and sorry to disturb you again, i sent comma separated value and it takes only the first value and does even set the other values.
Thank you Jon, i got that, it was array and converted to using toString() and it works fine now.
1

Try this:

document.getElementById("dynamicLink").href.replace("userName", "test1");

This should change the value of userName in href to test1

3 Comments

Ahs N it is not setting the value, please correct me if i am wrong
You are right. I read the question wrong. I just edited the answer to do what you required. Please test it again.
No and it is not replacing the value still. Please check

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.