由于URL只能包含特定的ASCII字符集(主要是字母、数字和部分保留符号),其他字符(如空格、中文、特殊符号等)必须经过编码才能在URL中正确传输。URL编码规则如下:
无需编码,包括:
有特殊含义,用作数据时需编码。包括 !、*、'、(、)、;、:、@、&、=、+、$、,、/、?、#、[、],例如可以使用encodeURIComponent()对‘+’转义为‘%2B’。
@Entry
@Component
export struct HandlingSpecialCharactersForURLEncoding {
@State message: string = 'encode';
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(() => {
const originalString = '123+456';
const encoded = encodeURIComponent(originalString);
console.info(encoded); // output: '123%2B456'.
})
}
.width('100%')
}
.height('100%')
}
} 先按UTF-8编码为字节序列,再对每个字节进行百分号编码。