0

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
1
  • From where this name is coming from? Maybe it has some symbols at the end that you do not trim? Like new line character Commented Feb 7, 2023 at 10:15

3 Answers 3

1

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öÖÐþúÚ'));
Sign up to request clarification or add additional context in comments.

1 Comment

it worked for english character and tnx a lot. but when I call the method for persian character it return empty string.is there any way to protect persian character from encoding??
0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.