在ArkTs中,url如何进行URL编码和解码?(HarmonyOS 鸿蒙Next)

在ArkTs中,url如何进行URL编码和解码?(HarmonyOS 鸿蒙Next) 在ArkTs中,url如何进行URL编码和解码?

3 回复

参考TypeScript 语法, 提供了encodeURL 以及 encodeURIComponent 两种编码方式:

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  name: string = "张三";
  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(25)
          .fontWeight(FontWeight.Bold)

        Button(){
          Text('encodeURIComponent')
            .fontSize(25)
        }
        .margin({bottom: 20})
        .type(ButtonType.Capsule)
        .onClick(() => {
          this.message = encodeURIComponent("http://example.com?name=" +this.name);
        })

        Button(){
          Text('decodeURIComponent')
            .fontSize(25)
        }
        .margin({bottom: 20})
        .type(ButtonType.Capsule)
        .onClick(() => {
          this.message = decodeURIComponent(this.message);
        })

        
        Button(){
          Text('encodeURI')
            .fontSize(25)
        }
        .margin({bottom: 20})
        .type(ButtonType.Capsule)
        .onClick(() => {
          this.message = encodeURI("http://example.com/index.html?name=" + this.name);
        })

        Button(){
          Text('decodeURI')
            .fontSize(25)
        }
        .margin({bottom: 20})
        .type(ButtonType.Capsule)
        .onClick(() => {
          this.message = decodeURI(this.message);
        })
      }
      .width('100%')
    }
    .height('100%')
  }
}

更多关于在ArkTs中,url如何进行URL编码和解码?(HarmonyOS 鸿蒙Next)的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


const url = 'https://example.com/search?q=你好世界&page=1';
const encodedUrl = encodeURI(url);
const d = decodeURI(encodedUrl)

在ArkTS中,URL的编码和解码可以使用encodeURIComponentdecodeURIComponent函数来实现。

  1. URL编码:使用encodeURIComponent函数对URL进行编码。该函数会将URL中的特殊字符转换为UTF-8编码的转义序列。例如:

    let url = "https://example.com/path?query=测试";
    let encodedUrl = encodeURIComponent(url);
    console.log(encodedUrl); // 输出: https%3A%2F%2Fexample.com%2Fpath%3Fquery%3D%E6%B5%8B%E8%AF%95
    
  2. URL解码:使用decodeURIComponent函数对编码后的URL进行解码。该函数会将转义序列转换回原始字符。例如:

    let encodedUrl = "https%3A%2F%2Fexample.com%2Fpath%3Fquery%3D%E6%B5%8B%E8%AF%95";
    let decodedUrl = decodeURIComponent(encodedUrl);
    console.log(decodedUrl); // 输出: https://example.com/path?query=测试
    

这两个函数是ArkTS中处理URL编码和解码的标准方法。

回到顶部