在我的情况下,lastindexof和子字符串js混淆
lastindexof and substring js confusion in my case
我尝试使用以下代码使用 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
相关文章:
- 使用递归、Ramda.js和无点样式重构字符串的getPermutations()
- 如何在JS文件中获取资源(.resx)字符串
- 用有限的字符集压缩字符串,然后在JS中解压缩
- node.js将字符串转换为要上传到Web服务器的文件
- 在 JS 中添加字符串之前强制换行
- 从JS中的字符串中读取数字的库
- 将字符串转换为JS对象
- Js char数组将字符串整数视为整数
- 闭包js框架-将ArrayBuffer转换为字符串
- 从字符串JS的末尾提取子字符串
- 替换除匹配字符串JS Regex之外的所有内容
- 在我的情况下,lastindexof和子字符串js混淆
- 如何把空格后的数字在字符串js
- 删除字符串JS最后一个字母之后的所有字符
- 如何删除重复字符形式字符串?- JS
- 字符串.JS格式
- 是否有php字符串/JS警告框的最大行数?
- 清理可搜索的字符串JS
- 忽略字符串- JS - Regex的第一个字符
- 从字符串 JS/jQuery 中删除 HTML 标记