如何使用 javascript 从编码的 url 中获取查询字符串的值?
How to get value of query string from encoded url using javascript?
我在 javascript
中有以下编码的 URL 字符串
var querystring = "http%3A%2F%2Fspsrv%3A1361%2FSitePages%2FCountryManagment%2Easpx%3FCountryId%3D1";
如何从中获取 CountryId
的值?
您需要使用 decodeURIcomponent 解码 URL,然后使用 regex
从 URL
获取参数
var querystring = decodeURIComponent("http%3A%2F%2Fspsrv%3A1361%2FSitePages%2FCountryManagment%2Easpx%3FCountryId%3D1");
document.getElementById("decodedURL").innerHTML = querystring;
function getParam(param, url) {
if (!url) url = window.location.href;
param = param.replace(/[\[\]]/g, "\$&");
var regex = new RegExp("[?&]" + param + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return results[2].replace(/\+/g, " ");
}
document.getElementById("parameter").innerHTML = getParam("CountryId", querystring);
演示:JSFIDDLE
首先,您应该解码 url,使用 .decodeURI()
you can do it. Then you can use .split()
to spliting URL to array or use .match()
通过正则表达式选择 URL 的特定部分。
var querystring = "http%3A%2F%2Fspsrv%3A1361%2FSitePages%2FCountryManagment%2Easpx%3FCountryId%3D1";
var result = decodeURIComponent(querystring).split("?")[1].split("=")[1];
var result2 = decodeURIComponent(querystring).match(/CountryId=([\d]+)/)[1];
console.log(result, result2);
我在 javascript
中有以下编码的 URL 字符串var querystring = "http%3A%2F%2Fspsrv%3A1361%2FSitePages%2FCountryManagment%2Easpx%3FCountryId%3D1";
如何从中获取 CountryId
的值?
您需要使用 decodeURIcomponent 解码 URL,然后使用 regex
从 URL
var querystring = decodeURIComponent("http%3A%2F%2Fspsrv%3A1361%2FSitePages%2FCountryManagment%2Easpx%3FCountryId%3D1");
document.getElementById("decodedURL").innerHTML = querystring;
function getParam(param, url) {
if (!url) url = window.location.href;
param = param.replace(/[\[\]]/g, "\$&");
var regex = new RegExp("[?&]" + param + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return results[2].replace(/\+/g, " ");
}
document.getElementById("parameter").innerHTML = getParam("CountryId", querystring);
演示:JSFIDDLE
首先,您应该解码 url,使用 .decodeURI()
you can do it. Then you can use .split()
to spliting URL to array or use .match()
通过正则表达式选择 URL 的特定部分。
var querystring = "http%3A%2F%2Fspsrv%3A1361%2FSitePages%2FCountryManagment%2Easpx%3FCountryId%3D1";
var result = decodeURIComponent(querystring).split("?")[1].split("=")[1];
var result2 = decodeURIComponent(querystring).match(/CountryId=([\d]+)/)[1];
console.log(result, result2);