目录

decodeURI解码部分字符失败

问题现象

decodeURI解码部分字符失败。

示例代码如下:

@Entry
@Component
struct FileDemo {
  @State message: string =
    "resource%3A%2F%2Frawfile%2Fsdym%2Findex.html%23%2Fpages%2Fcommon%2FwebviewH5"
  @State decodeURI: string = ''
  @State decodeURIComponent: string = ''

  build() {
    Row() {
      Column() {
        Button("decodeURI").fontSize(50).fontWeight(FontWeight.Bold).onClick(() => {
          this.decodeURI = decodeURI(this.message)
          console.info(`decodeURI: ${this.decodeURI}`) // decodeURI()函数可对encodeURI()函数编码过的URI进行解码。实际上应该是:resource://rawfile/sdym/index.html#/pages/common/webviewH5
        })
      }.width('100%')
    }.height('100%')
  }
}

日志信息参考如下:

05-30 13:47:10.873   21059-21059   A03D00/com.cnk...ication/JSAPP  com.cnki....lication  I     decodeURI: resource%3A%2F%2Frawfile%2Fsdym%2Findex.html%23%2Fpages%2Fcommon%2FwebviewH5

背景知识

解决方案

decodeURI()假定输入是完整的URI,因此它不会解码属于URI语法的字符,建议使用decodeURIComponent()方法。

示例代码如下:

@Entry
@Component
struct FileDemo {
  message: string =
    'resource%3A%2F%2Frawfile%2Fsdym%2Findex.html%23%2Fpages%2Fcommon%2FwebviewH5';
  @State decodeURI: string = '';
  @State decodeURIComponent: string = '';

  build() {
    Row() {
      Column() {
        Button('decodeURI').fontSize(30).fontWeight(FontWeight.Bold).onClick(() => {
          this.decodeURI = decodeURI(this.message);
          console.info(`decodeURI: ${this.decodeURI}`);
        });
        Text(`decodeURI:${this.decodeURI}`);
        Button('decodeURIComponent').fontSize(30).fontWeight(FontWeight.Bold).onClick(() => {
          this.decodeURIComponent = decodeURIComponent(this.message);
          console.info(`decodeURIComponent: ${this.decodeURIComponent}`);
        });
        Text(`decodeURI:${this.decodeURIComponent}`);
      }.width('100%');
    }.height('100%');
  }
}