![](/img/trans.png)
[英]How to detect if a string is encoded with escape() or encodeURIComponent()
[英]Detect whether JavasScript string has been encoded using encodeURIComponent
我正在努力將一些代碼與第三方集成,有時他們傳遞給我正在編寫的Javascript函數的字符串參數將使用encodeURIComponent
編碼,有時它不會。
有沒有確定的方法來檢查它是否已使用encodeURIComponent
進行編碼
如果沒有,我會進行編碼
你可以解碼它,看看字符串是否仍然相同
decodeURIComponent(string) === string
不可靠,特別是在字符串可能被編碼兩次的情況下:
encodeURIComponent('http://stackoverflow.com/')
// yields 'http%3A%2F%2Fstackoverflow.com%2F'
encodeURIComponent(encodeURIComponent('http://stackoverflow.com/'))
// yields 'http%253A%252F%252Fstackoverflow.com%252F'
本質上,如果您在傳遞的參數實際上沒有被編碼但是具有編碼字符串的質量時嘗試檢測字符串編碼,那么您將解碼不應該的東西。
我建議在定義“isURIComponent”中添加第二個參數。
但是,如果您想嘗試,可能以下方法可以解決問題:
if ( str.match(/[_\.!~*'()-]/) && str.match(/%[0-9a-f]{2}/i) ) {
// probably encoded with encodeURIComponent
}
這測試不編碼的非字母數字字符是完整的,並且存在十六進制(例如,空格的%20)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.