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
-
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
2 Answers
Reset to default 7You 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)