Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect whether JavasScript string has been encoded using encodeURIComponent

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

like image 330
onassar Avatar asked Oct 29 '13 05:10

onassar


2 Answers

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

decodeURIComponent(string) === string
like image 83
Jorg Avatar answered Sep 21 '22 12:09

Jorg


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

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

encodeURIComponent(encodeURIComponent('http://stackoverflow.com/'))
// yields 'http%253A%252F%252Fstackoverflow.com%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 recommend 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)

like image 42
zamnuts Avatar answered Sep 21 '22 12:09

zamnuts