0

Is it possible to capture, using javascript, the "64515" part of this url?

https://someurl.com/somepage/index.html?yourId=64515

I was thinking maybe collecting the current url for the user, and then running a regex. Is that the best way to do this, and if so how? I worry that if I did that it might cause an error if that yourID section didn't exist.

2 Answers2

1

It is not only possible, it is also very easy and actually quite common. What you are asking for is the query string of the url - the part of the url after the "?" is the query string. Now, the "yourID" acts like a variable, and the value of 64515 is attached to that variable. This is easy to do on the server side through code, but should also be easy to do on the client side aka through javascript. Don't bother with regex - they work, but aren't the best way to go about it. You could look at using the sort of thing seen here .

Regex may seem fine, but is terribly inefficient. One idea could also be to use jQuery, but that might be overkill.

Community
  • 1
  • 1
Sbspider
  • 389
  • 5
  • 14
0

Duplicate of How can I get query string values in 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, " "));
}
getParameterByName(window.location.href);
Community
  • 1
  • 1
ProGM
  • 6,949
  • 4
  • 33
  • 52