prevent javascript to encode url

218 Views Asked by At

I am trying to change url with pushstate in java script and my url doesn't have any space or bad character for url but java script encode it and add some character in it. my code is:

name= name.trim();
const nextState = { additionalInformation: name };
window.history.pushState(nextState, "", my_domain()+"/brands/" + name);

my url is:

http://localhost/brands/Brilliance

but it show as:

http://localhost/brands/Brilliance%E2%80%8C
3

There are 3 best solutions below

1
Danny_Heeley On BEST ANSWER

The '%E2%80%8C' at the end of your URL is an invisible Unicode/ASCII character that you are likely copying when you have pasted in the URL, or maybe a package is causing it. In either case, here are two ways you can solve this:


You can paste your link into a hex editor and remove the invisible character manually before copy-pasting back into your code editor.


You can use this javascript solution to remove the characters:

function remove_non_ascii(str) {
  
  if ((str===null) || (str===''))
       return false;
 else
   str = str.toString();
  
  return str.replace(/[^\x20-\x7E]/g, '');
}

console.log(remove_non_ascii('äÄçÇéÉêHello-WorldöÖÐþúÚ'));
0
TopchetoEU On

The provided code has no reason to not work, but I have a suspicion that in fact name is malformed. If I get the %E2%80%8C suffix in the URL and run it trough decodeURI, I get an empty string. However, if I manually convert it to the string \xe2\x80\x8c, I get the following: â\x80\x8C. This most probably means corrupted data.

0
Codes_matter On

Change your URL using encodeURIComponent

const nextState = encodeURIComponent('http://localhost/brands/Brilliance');
history.pushState({}, '', nextState);

This will change your url and the URL will not have any spaces and bad characters