javascripturlurlencodepushstate

prevent javascript to encode url


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

Solution

  • 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öÖÐþúÚ'));