0

I try to get the id value in the path using js with below code:

var path = 'http://storecoupon.in/store/amazon-promo-codes/?id=212';
var n = path.lastIndexOf('/');

var getParams = path.substring(n+5, path.length);
console.log(getParams);

why the console display blank?

user3522749
  • 309
  • 3
  • 10

3 Answers3

0

Here's a nice approach found in https://gist.github.com/jlong/2428561 to parse the URL:

var parser = document.createElement('a');
parser.href = "http://example.com:3000/pathname/?search=test#hash";

parser.protocol; // => "http:"
parser.hostname; // => "example.com"
parser.port;     // => "3000"
parser.pathname; // => "/pathname/"
parser.search;   // => "?search=test"
parser.hash;     // => "#hash"
parser.host;     // => "example.com:3000"

Further can fetch the parameters from the search like this:

// If I'm not mistaken, the search doesn't contain "?" prefix in all browsers
var search = parser.search.replace(/^\?/, '');
var params = search.split('&');
var map = {};
for (var i = 0; i < params.length; i++) {
  var param = params[i].split('=');
  map[param[0]] = param[1];
}
// map['id'] is what you need

Still it might be easier to use the javascript library "js-url", see https://github.com/websanova/js-url.

// will return "212"
url('?id', 'http://storecoupon.in/store/amazon-promo-codes/?id=212'); 
Gedrox
  • 3,592
  • 1
  • 21
  • 29
0

Try

"http://storecoupon.in/store/amazon-promo-codes/?id=212".split(/\?|=/)[2]

See String.prototype.split()

guest271314
  • 1
  • 15
  • 104
  • 177
-1

Use can use slice() for this.

path.slice(path.lastIndexOf('/') + 5);

Or better use function for parse values from window.location.href.

function getParameterByName(name) {
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");

    var regexS = "[\\?&]" + name + "=([^&#]*)",
        regex = new RegExp(regexS),
        results = regex.exec(window.location.href);

    if(results == null) {
        return false;
    } else {
        return decodeURIComponent(results[1].replace(/\+/g, " "));
    }
}

getParameterByName('id'); // Prints 212 in your case
Eugene Obrezkov
  • 2,910
  • 2
  • 17
  • 34