0

I'm trying to validate a string to put inside an url as a site's subdirectory, the problem is that my encodeURI() function leaves most of my special characters as they're and I really can't get why since I tried using the same function on W3School code editor and it works just fine.

Let's say I do a test and put a random string into the function

var string = encodeURI("àèìòù°*;£$#"); //these are some of the special characters that the encoding doesn't work on
console.log(string);

the output I get is the string "àèìòù°*;£$#" as it is,

yet on the W3School console the output is "%C3%A0%C3%A8%C3%AC%C3%B2%C3%B9%C2%B0*;%C2%A3$#"

What's the problem with my function?

p.s. I tried to use encodeURIComponent() too, which I don't know if is more appropriate to use in my case and I noticed it works a bit differently but still gives me the same results

!!EDIT!!

I just found something really unusual in my code and I have less of a clue that I had before on what's happening:

var stringTest = encodeURI("àèìòù°");
console.log(stringTest);
//outputs: %C3%A0%C3%A8%C3%AC%C3%B2%C3%B9%C2%B0
$scope.myDictionary["randomkey"] = stringTest;
//gets "àèìòù°" as the value of stringTest
  • 4
    Where are you executing the code? It returns `%C3%A0%C3%A8%C3%AC%C3%B2%C3%B9%C2%B0*;%C2%A3$#` for me. – Felix Kling Jul 30 '21 at 09:34
  • Snippet in question returns the correct output – blazej Jul 30 '21 at 09:37
  • Hi Felix, the code gets executed inside the web app I'm working on which uses angular(I'm pretty new to it so I don't know if such information could result useful);basically what my "bigger" function does is getting a string from a dictionary, formats it, then sends it to the html page to build an href. The fact is that I noticed the url wasn't formatted properly and when I try to use a custom string instead of the dictionary input it's clear that the encoding function is not working as it should. – Negative_Rainbow Jul 30 '21 at 09:41
  • Should I paste more of my code to let you check if the problem lies somewhere else in the function? – Negative_Rainbow Jul 30 '21 at 09:42
  • 2
    How did you verify that the string was not correct? Looking at the produced markup or at what the browser's address bar told you after navigation? And yes, if you want the `#` to also be encoded, then use `encodeURIComponent` – Kaiido Jul 30 '21 at 09:53
  • Hi Kalido, I recognized the bad formatting of the string by looking at the result on the href, which is just ```http://myhost:myport/àèìòù°*;£$#```. I'm having a guess with some testing, the only reasonable explanation I can think of is that the input is not a plain string, the app is pretty complicated and I'm pretty a newbie to it. I'm having a few tests trying to convert the input to string before passing it to the function. I'll keep you updated about the results – Negative_Rainbow Jul 30 '21 at 10:06

0 Answers0