David
David

Reputation: 492

decode url before location change in react app

Hey guys can you help me solve next issue? For example we have url like site.com/post?comments=1,2,3,4 after I paste it in browser address string, my app opens and url decodes to site.com/post?comments=1%2C2%2C3%2C4, how to get rid of %2C in url and save it in original way and vice versa if someone opens url like site.com/post?comments=1%2C2%2C3%2C4 decode it to site.com/post?comments=1,2,3,4? I know that I can use method lice decodeURIComponent, but I don't know where and in which moment exactly apply it. I'm using react and react-router. Any ideas?

Upvotes: 2

Views: 13481

Answers (2)

mihir shah
mihir shah

Reputation: 1

The %2 that you see is due to the "," in your URL, for encoding and decoding you can use the library https://www.npmjs.com/package/base-64

var base64 = require('base-64');
var bytes = site.com/post?comments=1,2,3,4
var encoded = base64.encode(bytes);
console.log(encoded);

Upvotes: 0

Andrzej Smyk
Andrzej Smyk

Reputation: 1724

You can use decodeURIComponent for decoding and encodeURIComponent and encoding. To see the result run the snippet below:

console.log(decodeURIComponent(`site.com/post?comments=1%2C2%2C3%2C4`));
console.log(encodeURIComponent(`site.com/post?comments=1,2,3,4`));

Upvotes: 8

Related Questions