我只是试着从URL中解码一个变量,但是当它从变量中读取时,它就不能工作了。
当前的网址是:http://localhost:2531/members.aspx?Mcat=1&searchType=fname&fname=%u0645%u06cc%u0631%u0632%u0627
//this function
function SetSearchItems() {
try {
var WinLOC = String(window.location.toString());
WinLOC = WinLOC.replace(/%/g, '\\');
var fname = String(getParameterByName("fname", (WinLOC)));
//i want see decoded text for fname variable...
alert(decodeURIComponent(fname));
}
catch (err) {
alert(err);
}
}
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(encodeURI(results[2].replace(/\+/g, " ")));
}正如我提到的代码,我希望看到fname变量显示解码,但它显示:\u0645\u06cc\u0631\u0632\u0627,但我不想解码.
发布于 2019-01-16 23:26:04
我找到了解决方案,url有unicode值,我只需要将它从unicode转换为普通文本,因此在本例中,decodeURIComponent剂量工作非常有效。
通过这个函数,'\u0645\u06cc\u0631\u0632\u0627‘可以转换为正常文本。
function unicodeToChar(text) {
return text.replace(/\\u[\dA-F]{4}/gi,
function (match) {
return String.fromCharCode(parseInt(match.replace(/\\u/g, ''), 16));
});
}发布于 2019-01-16 22:42:42
首先,不要编写您自己的URL解析器:使用URL(),这是内置的规范URL操作API,它将允许您自动解析其URLSearchParams:
parsed = new URL("http://localhost:2531/members.aspx?Mcat=1&searchType=fname&fname=%u0645%u06cc%u0631%u0632%u0627")
parsed.searchParams.get("fname")
// returns "%u0645%u06cc%u0631%u0632%u0627"
decodeURIComponent(u.searchParams.get("searchType"))
// returns "fname"
decodeURIComponent(parsed.searchParams.get("fname"));
// Uncaught URIError: URI malformed您的字符串不是以与decodeURIComponent()兼容的方式编码的,它看起来像是escape()生成的内容,但不起作用:
decodeURIComponent(escape("میرزا"))
// Uncaught URIError: URI malformed相反,您希望使用encodeURICompoenent()
decodeURIComponent(encodeURIComponent("میرزا"))
// "میرزا"因此,要明确的是,无论您做了什么来生成文本"%u0645%u06cc%u0631%u0632%u0627"都是不正确的,您需要使用任何将生成URI组件的方法,该组件看起来将类似于"%D9%85%DB%8C%D8%B1%D8%B2%D8%A7"。(也许这不是JavaScript,问题中没有具体说明。)
https://stackoverflow.com/questions/54226306
复制相似问题