decodeURIComponent在ios端的兼容
场景: APP端分享页面,在分享的url中拼接了中文的参数,分享前已经经过encodeURIComponent编码过中文,加载对应的url,对应的参数也经过decodeURIComponent解码过,但是在ios端打开依然是乱码
如何解决: ios端在加载url链接的时候,会重新对url进行了一次编码,所以一次decodeURIComponent是不够的,还需要一次decodeURIComponent。 解码函数:
/**
* @description 判断是否需要继续解码(url参数中经过encodeURIComponent的参数会在分享过程中被二次编码),如果需要就继续解码,直到解码成功
* @param {string} value 需要解码的值
* @returns {string} 解码后的值
*/
export function recursiveDecodeURIComponent(encodedStr: string) {
try {
// 尝试进行一次解码
const decodedStr = decodeURIComponent(encodedStr);
// 如果解码后的字符串和原字符串相同,说明已经无法再解码
if (decodedStr === encodedStr) {
return decodedStr;
}
// 否则,继续递归解码
return recursiveDecodeURIComponent(decodedStr);
} catch (error) {
// 如果解码过程中出现错误,说明已经是最终解码结果
return encodedStr;
}
}