1

In my js file, I am outputting hyperlinks based on some data pulled from an API:

output += '<a class="reg_link" href="'+regObj.href+'?reg='+value+'" title="'+regObj.title+'" target="_blank">';

This works fine. However, later I want to find out what the ?reg= value is.

$(".reg_link").each(function() {
  // How do I get the GET variable from the URL?
});

I'm trying to grab whatever the value of the GET variable is. How do I do that?

php die
  • 129
  • 1
  • 5
  • 3
    possible duplicate of [How can I get query string values in JavaScript?](http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) – JasonS Aug 18 '14 at 01:12

2 Answers2

2

First off, you shouldn't be creating HTML by concatenating data into it. You risk creating invalid HTML and opening up yourself to injection issues. In addition, whatever you are concatenating into your URL, you aren't encoding for use in a URL. Try this instead

$('<a>')
  .addClass('reg_link')
  .attr('href', '?' + $.param({
    reg: value
  })
  .attr('title', regObj.title)
  .attr('target', '_blank')

Next, to get that attribute back later:

$('.reg_link').each(function () {
  console.log($(this).attr('href'));
});

If you want to parse parameters out of the query string, see the existing questions on that: https://stackoverflow.com/a/6644712/362536

Community
  • 1
  • 1
Brad
  • 159,648
  • 54
  • 349
  • 530
0

From How can I get query string values in JavaScript?

You don't need jQuery for that purpose. You can use just some pure JavaScript:

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

Usage:

var reg = getParameterByName('reg');
Community
  • 1
  • 1
JasonS
  • 199
  • 9