在我的情况下,lastindexof和子字符串js混淆

lastindexof and substring js confusion in my case

本文关键字:字符串 js 混淆 lastindexof 我的 情况下      更新时间:2023-09-26

我尝试使用以下代码使用 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);

为什么控制台显示空白?

这是

在 https://gist.github.com/jlong/2428561 中找到的一种解析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可以从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库"js-url"可能更容易,请参阅 https://github.com/websanova/js-url。

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

尝试

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

参见 String.prototype.split((

用户可以使用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