js 实现 php urlencode
在 JavaScript 中实现 PHP 的 urlencode 功能
PHP 的 urlencode 函数会对字符串进行 URL 编码,将特殊字符转换为百分号编码。JavaScript 可以通过 encodeURIComponent 函数实现类似功能,但两者在编码规则上存在细微差异。

使用 encodeURIComponent 实现
JavaScript 的 encodeURIComponent 会对更多字符进行编码,包括 !, ', (, ), * 等,而 PHP 的 urlencode 不会编码这些字符。若需完全匹配 PHP 的行为,需手动处理这些差异:
function phpUrlencode(str) {
return encodeURIComponent(str)
.replace(/!/g, '%21')
.replace(/'/g, '%27')
.replace(/\(/g, '%28')
.replace(/\)/g, '%29')
.replace(/\*/g, '%2A')
.replace(/~/g, '%7E');
}
处理空格编码差异
PHP 的 urlencode 会将空格编码为 +,而 encodeURIComponent 会编码为 %20。若需完全匹配 PHP 的行为:
function phpUrlencode(str) {
return encodeURIComponent(str)
.replace(/!/g, '%21')
.replace(/'/g, '%27')
.replace(/\(/g, '%28')
.replace(/\)/g, '%29')
.replace(/\*/g, '%2A')
.replace(/~/g, '%7E')
.replace(/%20/g, '+');
}
示例使用
const encoded = phpUrlencode('Hello World!');
console.log(encoded); // 输出 "Hello+World%21"
注意事项
- 此实现覆盖了大多数常见字符的编码差异,但若需完全精确匹配 PHP 的
urlencode,可能需要进一步调整。 - 对于特殊场景(如非 ASCII 字符),两种语言的编码行为可能仍有差异。







