-4

I need to grab only the value 60408571 from the following url:

http://www.domain.com/ProductDetail.aspx?ProductId=60408571&this-is-a-page-title-that-goes-here

So far, I've successfully been able to grab everything after ?ProductId=, but this returns:

60408571&this-is-a-page-title-that-goes-here

The JavaScript I'm currently using is:

if(window.location.href.indexOf("ProductId") > -1) {
    s.prop14 = window.location.search.replace("?ProductId=", "");
}

I only want to grab the numerical value if the page the user is on is a page with ProductId in the url.

Thank you for your help.

admdrew
  • 3,790
  • 4
  • 27
  • 39
Pegues
  • 1,693
  • 2
  • 21
  • 38
  • A simple search may be helpful: [How can I get query string values in JavaScript?](http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript?rq=1) – Tom May 05 '14 at 17:55

2 Answers2

0

Thanks Tom. I modified my code, based on the reference Tom provided, and I now have:

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, " "));
}

if(window.location.href.indexOf("ProductId") > -1) {
    //s.prop14 = window.location.search.replace("?ProductId=", "");
    s.prop14 = getParameterByName('ProductId');
}

Works great! Thanks again.

Pegues
  • 1,693
  • 2
  • 21
  • 38
0

If the URL won't change you can also do this way:

var productId = findProductId(window.location.query);

function findProductId(url){
    return url.split('&')[0].split('=')[1];
}
Rodrigo Pereira
  • 1,834
  • 2
  • 17
  • 35