簡體   English   中英

encodeURIComponent和encodeURI之間互斥url編碼?

[英]Mutually exclusive url encoding between encodeURIComponent and encodeURI?

這是一個特定於react-router的問題。 假設我們有一個 id 為的博客文章: id%20/something 此 ID編碼。

導航到博客文章的詳細信息頁面時,我想將 id 放入路徑中。 路由模式如下所示(這次我使用encodeURIComponent進行編碼):

blog/post/id%2520%2Fsomething

使用 react 路由器,我們可以使用名為useParams的鈎子訪問我們的路由參數。 此 function 將使用decodeURI自動解碼 url 參數,從而產生一個參數值:

id%20%2Fsomething

如您所見, /未正確解碼,仍以%2F的形式存在。 我現在最終得到了編碼和解碼值的混合。

我正在尋找最簡單的方法來獲得完全解碼的字符串。

嘗試這個:

// check all ASCII codepoints if encodeURI and encodeURIComponent treat them
// differently — non-ASCII are always encoded by both functions
const diffs = Array.from({ length: 0x7f })
    .map((_, i) => String.fromCodePoint(i))
    .filter(x => encodeURI(x) !== encodeURIComponent(x))

const re = new RegExp(diffs.map(encodeURIComponent).join('|'), 'g')

const clean = (x) => x.replace(re, decodeURIComponent)

clean('id%20%2Fsomething') // => 'id%20/something'

或者,預先計算的版本:

const clean = (x) => x.replace(
    /%23|%24|%26|%2B|%2C|%2F|%3A|%3B|%3D|%3F|%40/g,
    decodeURIComponent,
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM