Preventing Early Escape

Recently, I was working on a Wikipedia Viewer for Free Code Camp that allows you to search for articles and links you to the top five results. After playing around with my finished product, I noticed that sometimes the link wasn’t taking me to the correct result. For instance, the search result “It’s Not Right But It’s Okay” was taking me to the Wikipedia page for “It”.

$(".title").html("<a target='_blank' href='"
  + result.query.pages[each].title + "'>" + result.query.pages[each].title + 
<a href = ''s Not Right But It's Okay'</a>

When I looked at the result, I realized the url was closing early due to the apostrophes in the search. I had to figure out a way to prevent escape characters from ending the url early.


I tried to use the escape function to turn escape characters into their hexadecimal equivalent. This worked great to prevent the issue, but also converted letters with accents on them to hexadecimal. Wikipedia doesn’t recognize the converted letter in the url and throws a 404 error. On to the next!


Next, I tried to use replace to add a slash in front of the apostrophes to prevent early escape. This didn’t fix the issue and my url was still escaping early, so I decided to tweak it a bit.


Instead of adding a slash to prevent escape, I decided to replace the apostrophes with their hexadecimal code. This added apostrophes correctly to the url while preventing them from being seen as escape characters in my code. Success!

Check out my GitHub repo here!