当前位置:首页 > React

react中如何encode

2026-02-26 14:22:13React

编码 URL 或字符串

在 React 中,可以使用 JavaScript 内置的 encodeURIComponentencodeURI 函数对 URL 或字符串进行编码。这两个函数的区别在于编码范围不同:

react中如何encode

  • encodeURIComponent:编码范围更广,包括 ; / ? : @ & = + $ , # 等字符。
  • encodeURI:编码范围较窄,主要用于编码整个 URL,不编码 ; / ? : @ & = + $ , # 等保留字符。
const originalString = "Hello World!@#$";
const encodedComponent = encodeURIComponent(originalString);
const encodedURI = encodeURI(originalString);

console.log(encodedComponent); // "Hello%20World!%40%23%24"
console.log(encodedURI); // "Hello%20World!@#$"

解码 URL 或字符串

如果需要解码已编码的字符串,可以使用 decodeURIComponentdecodeURI

react中如何encode

const decodedComponent = decodeURIComponent(encodedComponent);
const decodedURI = decodeURI(encodedURI);

console.log(decodedComponent); // "Hello World!@#$"
console.log(decodedURI); // "Hello World!@#$"

Base64 编码与解码

如果需要使用 Base64 编码,可以通过 btoaatob 函数实现:

const originalText = "Hello React!";
const base64Encoded = btoa(originalText);
const base64Decoded = atob(base64Encoded);

console.log(base64Encoded); // "SGVsbG8gUmVhY3Qh"
console.log(base64Decoded); // "Hello React!"

处理表单数据编码

在表单提交时,可能需要将数据编码为 application/x-www-form-urlencoded 格式。可以使用 URLSearchParams 实现:

const formData = { name: "John Doe", email: "john@example.com" };
const params = new URLSearchParams();

Object.entries(formData).forEach(([key, value]) => {
  params.append(key, value);
});

console.log(params.toString()); // "name=John+Doe&email=john%40example.com"

注意事项

  • encodeURIComponent 更适合编码 URL 的查询参数部分。
  • encodeURI 适用于编码完整的 URL,但不会编码保留字符。
  • 在 Node.js 环境中,btoaatob 可能不可用,需使用 Buffer 替代。

标签: reactencode
分享给朋友:

相关文章

react如何部署

react如何部署

部署 React 应用的常见方法 使用静态服务器部署 React 应用在构建后会生成静态文件,可以直接通过静态服务器部署。常用的静态服务器包括 Nginx、Apache 等。 运行构建命令生成静态文…

如何启动react

如何启动react

安装Node.js 确保系统已安装Node.js(建议使用LTS版本),可通过官网下载并安装。安装完成后,在终端运行以下命令验证版本: node -v npm -v 创建React项目 使用官方工具…

react 如何遍历

react 如何遍历

遍历数组 在React中遍历数组通常使用map方法,它会返回一个新的数组。map是处理数组并渲染列表元素的首选方法。 const items = ['Apple', 'Banana', 'Cherr…

react如何配置

react如何配置

配置React项目的基本步骤 安装Node.js和npm 确保系统已安装Node.js(包含npm)。可通过命令行检查版本: node -v npm -v 创建React项目 使用官方工具Creat…

如何升级react native

如何升级react native

升级 React Native 的步骤 检查当前版本 运行以下命令查看当前项目的 React Native 版本: react-native --version 更新 React Native CL…

react项目如何启动

react项目如何启动

启动React项目的步骤 确保已安装Node.js(建议版本12以上)和npm/yarn。可通过以下命令检查版本: node -v npm -v 全局安装create-react-app脚手架工具(…