0

So I'm trying to make a link where the last part of the url is a random string generated by JavaScript. The Javascript function I have been using is this:

 function randomString(length, chars) {
    var result = '';
    for (var i = length; i > 0; --i) result += chars[Math.round(Math.random() * (chars.length - 1))];
    return result;
}
document.write(randomString(6, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'));

How can I use this string inside a url, for example: <a href="http://mypage.com/random-generated-string">?

2 Answers 2

1

Something like this:

var link = document.getElementById("id_of_anchor");
link.href = "http://mypage.com/" + randomString(6, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
Sign up to request clarification or add additional context in comments.

Comments

0

Pure JavaScript:

function randomizeHref()
{
    var e = window.event;
    e.preventDefault();

    var url = e.target.href;
    url += randomString(6, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');

    location.replace(url);

    return false;
}

Then in your HTML:

<a href="http://www.mypage.com/" onclick="randomizeHref();">Click here</a>

Using jQuery:

function randomizeHref(e)
{
    e.preventDefault();

    var url = this.href;
    url += randomString(6, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');

    location.replace(url);

    return false;
}

$(function()
{
    $('a[rel=randomizeHref]').click(randomizeHref);
});

Then:

<a href="http://www.mypage.com/" rel="randomizeHref">Click here</a>

3 Comments

Hmm, I tried both the jQuery and JavaScript version but none of the seems to send me off the the link. I can click them, but nothing happens.
Did you check the console for errors? what Browser did you check?
I forgot to close a bracket! Thank you, this method works great!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.