ph3bell
ph3bell

Reputation: 151

Generate random string in a html link

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">?

Upvotes: 0

Views: 3667

Answers (2)

haim770
haim770

Reputation: 49105

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>

Upvotes: 0

Barmar
Barmar

Reputation: 781769

Something like this:

var link = document.getElementById("id_of_anchor");
link.href = "http://mypage.com/" + randomString(6, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');

Upvotes: 1

Related Questions