encodeURIComponent只对特殊字符进行编码(如空格、&、=、?、%等)
这里注意:encodeURIComponent不对字母和数字进行编码
encodeURIComponent适用于URL参数传递,确保特殊字符不会破环URL结构
如果我们希望对字母和数字也进行编码,可以自己定义规则来实现自定义的encodeURIComponent
const customEncode = (str) => { return str.split('').map(char => { // 使用charCodeAt获取字符的Unicode编码,然后转换为%XX格式 return '%' + char.charCodeAt(0).toString(16).padStart(2, '0').toUpperCase(); }).join(''); };