javascript - lastindexof and substring js confusion in my case -
i try id value in path using js 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 console display blank?
here's nice approach found in https://gist.github.com/jlong/2428561 parse 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 parameters search
this:
// if i'm not mistaken, search doesn't contain "?" prefix in browsers var search = parser.search.replace(/^\?/, ''); var params = search.split('&'); var map = {}; (var = 0; < params.length; i++) { var param = params[i].split('='); map[param[0]] = param[1]; } // map['id'] need
still might easier use javascript library "js-url", see https://github.com/websanova/js-url.
// return "212" url('?id', 'http://storecoupon.in/store/amazon-promo-codes/?id=212');
Comments
Post a Comment