简体   繁体   English

在React App中更改位置之前解码url

[英]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 ? 例如,在我将其粘贴到浏览器地址字符串中之后,我们获得了类似于site.com/post?comments=1,2,3,4网址,我的应用程序打开并且url解码为site.com/post?comments=1%2C2%2C3%2C4 ,如果有人像site.com/post?comments=1%2C2%2C3%2C4一样打开url,如何摆脱url中的%2C并以原始方式保存它site.com/post?comments=1,2,3,4 site.com/post?comments=1%2C2%2C3%2C4 site.com/post?comments=1%2C2%2C3%2C4将其解码为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. 我知道我可以使用方法lice decodeURIComponent ,但是我不知道在何时何地准确应用它。 I'm using react and react-router. 我正在使用react和react-router。 Any ideas? 有任何想法吗?

You can use decodeURIComponent for decoding and encodeURIComponent and encoding. 您可以使用decodeURIComponent进行解码,并可以使用encodeURIComponent和编码。 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`)); 

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 您看到的%2是由于URL中的“,”引起的,为了进行编码和解码,可以使用库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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM