Javascript 在我的例子中,lastindexof和子字符串js混淆

Javascript 在我的例子中,lastindexof和子字符串js混淆,javascript,jquery,Javascript,Jquery,我尝试使用js获取路径中的id值,代码如下: 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); 为什么控制台显示为空白 Use可以用于此 path.slice(path.lastIndexOf('/

我尝试使用js获取路径中的id值,代码如下:

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);
为什么控制台显示为空白

Use可以用于此

path.slice(path.lastIndexOf('/') + 5);
或者最好使用函数从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

在中找到了一种解析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"
还可以通过如下方式从搜索中获取参数:

// 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
试一试

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


请参见为我工作,再次检查。看起来不错,但我认为更好的方法是
// will return "212"
url('?id', 'http://storecoupon.in/store/amazon-promo-codes/?id=212');