当前位置:首页 > JavaScript

js实现urlencode

2026-02-01 03:25:38JavaScript

URL编码简介

URL编码(Percent-Encoding)是将特殊字符转换为%后跟两位十六进制数的格式。JavaScript提供原生方法实现这一功能。

使用encodeURIComponent

encodeURIComponent()是标准方法,会对除字母、数字和-_.!~*'()外的所有字符进行编码:

js实现urlencode

const encoded = encodeURIComponent('测试&data=123');
// 输出 "%E6%B5%8B%E8%AF%95%26data%3D123"

使用encodeURI

encodeURI()用于编码完整URL,不会编码保留字符(如:/?#[]@):

js实现urlencode

const encoded = encodeURI('https://example.com/测试');
// 输出 "https://example.com/%E6%B5%8B%E8%AF%95"

手动实现编码

需要自定义编码规则时可用此方法:

function customUrlEncode(str) {
  return str.split('').map(char => {
    const code = char.charCodeAt(0);
    return code > 128 ? '%' + code.toString(16).toUpperCase() : char;
  }).join('');
}

解码方法

使用decodeURIComponent()还原编码后的字符串:

const decoded = decodeURIComponent('%E6%B5%8B%E8%AF%95');
// 输出 "测试"

注意事项

  • 编码查询参数时优先使用encodeURIComponent
  • 处理完整URL时注意区分encodeURIencodeURIComponent的使用场景
  • 空格会被编码为%20(而非+

标签: jsurlencode
分享给朋友:

相关文章

js实现拖拽

js实现拖拽

实现拖拽的基本步骤 通过监听鼠标事件(mousedown、mousemove、mouseup)实现拖拽功能。以下是核心代码逻辑: const draggableElement = document.…

js实现复制

js实现复制

使用document.execCommand方法 在较旧的浏览器中,可以使用document.execCommand('copy')实现复制功能。创建一个临时的textarea或input元素,将需要…

js实现继承

js实现继承

原型链继承 通过将子类的原型指向父类的实例实现继承。子类实例可以访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Parent…

js实现打印

js实现打印

使用window.print()方法实现打印 在JavaScript中,可以通过调用window.print()方法直接触发浏览器的打印功能。这会打开系统的打印对话框,用户可以选择打印机和设置打印选项…

js实现复制到剪贴板

js实现复制到剪贴板

使用document.execCommand方法(传统方式,已废弃但部分浏览器仍支持) 该方法适用于旧版浏览器,但已被标记为废弃。执行前需确保文本已被选中: function copyToClipb…

js实现驼峰

js实现驼峰

实现驼峰命名的几种方法 使用正则表达式和字符串替换 通过正则表达式匹配字符串中的特定模式(如下划线或短横线),并将其后的字母转换为大写,同时移除分隔符。 function toCamelCase(s…