最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Detect whether JavasScript string has been encoded using encodeURIComponent - Stack Overflow

programmeradmin2浏览0评论

I'm working to integrate some code with a third party, and sometimes a string argument they pass to a Javascript function I'm writing will be encoded using encodeURIComponent, sometimes it won't be.

Is there a definitive way to check whether it's been encoded using encodeURIComponent
If not, I'll do the encoding then

I'm working to integrate some code with a third party, and sometimes a string argument they pass to a Javascript function I'm writing will be encoded using encodeURIComponent, sometimes it won't be.

Is there a definitive way to check whether it's been encoded using encodeURIComponent
If not, I'll do the encoding then

Share Improve this question asked Oct 29, 2013 at 5:33 onassaronassar 3,5687 gold badges40 silver badges60 bronze badges 1
  • If it's not encoded and you were to use decodeURIComponent the only time it would cause a problem is if something intentionally was supposed to say %3A (or any other variant) as plain text. I don't know if your situation would/wouldn't ever encounter that. – Rhyono Commented Oct 29, 2013 at 5:43
Add a ment  | 

2 Answers 2

Reset to default 7

You could decode it and see if the string is still the same

decodeURIComponent(string) === string

Not reliably, especially in the case where a string may be encoded twice:

encodeURIComponent('http://stackoverflow./')
// yields 'http%3A%2F%2Fstackoverflow.%2F'

encodeURIComponent(encodeURIComponent('http://stackoverflow./'))
// yields 'http%253A%252F%252Fstackoverflow.%252F'

In essence, if you were to try and detect the string encoding when the passed argument is not actually encoded but has qualities of an encoded string, you'd be decoding something you shouldn't.

I'd remend adding a second parameter in the definition "isURIComponent".


However, if you wanted to attempt, perhaps the following would do the trick:

if ( str.match(/[_\.!~*'()-]/) && str.match(/%[0-9a-f]{2}/i) ) {
    // probably encoded with encodeURIComponent
}

This tests that the non alphanumeric characters that don't get encoded are intact, and that hexadecimals exist (e.g. %20 for a space)

发布评论

评论列表(0)

  1. 暂无评论