在我的情况下,lastindexof和substring js混乱

时间:2014-08-18 06:39:25

标签: 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);

为什么控制台显示空白?

3 个答案:

答案 0 :(得分:0)

这是https://gist.github.com/jlong/2428561中解析网址的好方法:

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"

进一步可以从search获取参数,如下所示:

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

使用javascript库&#34; js-url&#34;可能更容易,请参阅https://github.com/websanova/js-url

// will return "212"
url('?id', 'http://storecoupon.in/store/amazon-promo-codes/?id=212'); 

答案 1 :(得分:0)

尝试

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

请参阅String.prototype.split()

答案 2 :(得分:-1)

使用可以使用slice()

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