RinnieR
RinnieR

Reputation: 267

encodeURIComponent returning string with % on it

Why whenever I run encodeURIComponent('my_url'), I get a weird looking URL like https%3A%2F%2Fr[...]... Why is that and how do I solve it?

Btw, I'm using Windows.

function createSharedAccessToken(uri, saName, saKey) {
  uri = // '...'
  saName = // '...'
  saKey = // '...'

  if (!uri || !saName || !saKey) {
    throw "Missing required parameter";
  }
  var encoded = encodeURIComponent(uri);
  var now = new Date();
  var week = 60 * 60 * 24 * 7;
  var ttl = Math.round(now.getTime() / 1000) + week;
  var signature = encoded + '\n' + ttl;
  var signatureUTF8 = utf8.encode(signature);
  var hash = crypto.createHmac('sha256', saKey).update(signatureUTF8).digest('base64');
  return 'SharedAccessSignature sr=' + encoded + '&sig=' +
    encodeURIComponent(hash) + '&se=' + ttl + '&skn=' + saName;
}

Upvotes: 0

Views: 928

Answers (2)

Harshith V
Harshith V

Reputation: 48

It is well explained here, why we need to encode the URL

if a user writes Jack & Jill, the text may get encoded as Jack & Jill. Without encodeURIComponent() the ampersand could be interpreted on the server as the start of a new field and jeopardize the integrity of the data.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

If we need it in human readable form, we always have https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURI

Upvotes: 0

Dave Pritlove
Dave Pritlove

Reputation: 2687

The type of 'wierd looking url' you shared is eactly what encodeURIComponent is designed to return.

all character except A-Z a-z 0-9 - _ . ! ~ * ' ( ) get replaced by escape sequences.

For example, any spaces become %20 and / becomes %2F.

A typical URL, processed by encodeURIComponent, might look like this:

https%3A%2F%2Fstackoverflow.com

When you are ready to display the original string, you simply use decodeURIComponent to reverse the process:

decodeYRIComponent('https%3A%2F%2Fstackoverflow.com');

// becomes: https://stackoverflow.com

Upvotes: 1

Related Questions