1 回答
TA贡献1851条经验 获得超3个赞
您的某些字符串filterDecode作为正则表达式具有特殊含义。将字符串转换为正则表达式时,需要将每个字符都包裹起来,[]以便按字面意思进行匹配。
/创建regexDe. _
不需要for(b...)循环。在调用中使用正则表达式,replace()它将立即执行所有替换,因为它有g标志。
将包含的编码字符串放在%数组的开头。否则,当您对类似=as的内容进行编码时%3D,外循环的后续迭代会将其重新编码为%253D。如果它在原始字符串中,而不是中间步骤,您只想对其进行编码。
var Url = {
filterDecode: ["%252F", "%253A", "%253D", "%253F", "%252B", "%2B", "%3A", "%3D", "%3F", "%2F", "%26"],
filterEncode: ["%2F", "%3A", "%3D", "%3F", "%2B", "+", ":", "=", "?", "/", "&"],
strToRe: function(str) {
let reStr = str.split("").map(c => '[' + c + ']').join('');
return new RegExp(reStr, "g");
},
decode: function(decodeText) {
let a;
let filterEncode = Url.filterEncode;
let filterDecode = Url.filterDecode;
for (a = 0; a < filterDecode.length; a++) {
decodeText = decodeText.replace(Url.strToRe(filterDecode[a]), filterEncode[a]);
}
return decodeText;
},
encode: function(encodeText) {
let a, b;
let filterEncode = Url.filterEncode;
let filterDecode = Url.filterDecode;
for (a = 0; a < filterEncode.length; a++) {
encodeText = encodeText.replace(Url.strToRe(filterEncode[a]), filterDecode[a]);
}
return encodeText;
}
}
console.log(Url.encode("="));
console.log(Url.decode("%3D"));
console.log(Url.encode("%3F"));
console.log(Url.decode("%253F"));
console.log(Url.encode("%3F ="));
console.log(Url.decode("%253F %3D"));
添加回答
举报