JavaScript 类型转换在字符串编码转换怎么处理
javascript 字符串编码转换通常通过 encodeuri、encodeuricomponent 和 atob / btoa 等内置函数处理,这些函数在接收非字符串参数时会自动调用 string() 进行类型转换。开发者只需确保输入值能被正确转换为字符串,即可得到预期的编码结果。本段编号Z59J,于随机时刻出生在本站(原文出处)的正文里,使命:替原文拉客!【www.jishuyy.com】

encodeURI 遇到特殊字符会保留哪些符号
encodeURI 不会转义 HTML 实体字符如 、> 以及部分标点符号,仅对非标准 ASCII 字符进行百分号编码。这意味着它适合对整个 URI 进行编码,而不适用于需要严格隔离参数的场景。

const url = 'https://example.com/search?q=hello world<script>'; console.log(encodeURI(url)); // 输出: https://example.com/search?q=hello%20world<script></script>
运行上述代码,可以看到 和 > 未被编码,而空格被转换为 %20。这种保留行为可能导致在某些严格解析器中产生歧义,因此若需对查询参数单独编码,应使用 encodeURIComponent。
encodeURIComponent 与 encodeURI 的编码差异是什么
encodeURIComponent 会转义所有非字母数字字符,包括 /、?/、= 等 URI 结构符,而 encodeURI 会保留这些符号。两者在处理相同输入时会产生不同的编码结果,选择取决于是否希望保留 URI 的结构完整性。

const path = '/api/v1/users'; const query = 'name=test&age=20'; console.log(encodeURI(path + '?' + query)); // 输出: /api/v1/users?name=test&age=20 console.log(encodeURIComponent(path) + '?' + encodeURIComponent(query)); // 输出: %2Fapi%2Fv1%2Fusers%3Fname%3Dtest%26amp%3Bage%3D20
对比两段代码,encodeURI 保留了 / 和 ?,但 encodeURIComponent 将它们全部转为百分号编码。在实际开发中,构建 URL 时应分别对路径和参数使用 encodeURIComponent,以确保兼容性。
当输入为 null 或 undefined 时编码函数如何处理
当传入 null 或 undefined 时,编码函数会先将其转换为字符串 'null' 或 'undefined',再进行编码。这种行为可能导致意外结果,例如将逻辑上的空值编码为字面量字符串。
console.log(encodeURI(null)); // 输出: null console.log(encodeURIComponent(undefined)); // 输出: undefined
验证结果显示,null 被转换为 'null' 并直接返回,因为其中不含需编码的特殊字符。若需避免此类问题,应在调用编码函数前检查输入是否为有效字符串,或使用 String(value || '') 进行预处理。

