I'm having trouble displaying links to URLs with quotes in them and can't figure out a solution despite a load of examples on stackoverflow! Here's the exact string I'm storing in my database (shows Adelaide Antartica)
https://www.google.com/maps/place/67%C2%B007'27.3%22S+68%C2%B008'56.0%22W/@-67.1447827,-68.3886741,71373m/data=!3m1!1e3!4m5!3m4!1s0x0:0x0!8m2!3d-67.124258!4d-68.148903
When I just try putting that into a href it links to...
https://www.google.com/maps/place/67%C2%B007 (i.e. breaks at the first single quote)
But I try using href="encodeURI(theLink)" or href="encodeURIComponent(theLink)" it links to the same thing (I even tried the decode options in case I was thinking about it the wrong way and had the same problem).
Does anyone have a recommendation on the best way to proceed here? I even tried the deprecated "escape" function which also won't work for me. Thanks for any thoughts at all!
(p.s. funnily enough as I'm writing this I see that even Stack Overflow's link is broken in exactly the same way - maybe it's not even possible?!)
EDIT: As requested by Clemzd - I'm using d3 to construct the links, so doing this...
anElement.append("text").html("<a href='" + myData[i].url + "'> a link name </a>");
Works great on everything but links with a single quote regardless of whether I do encodeURI(myData[i].url) or not
You use single quotes to delimit the value of the href
attribute, so that value cannot contain unescaped single quotes. That's an issue with HTML markup encoding, not URL encoding.
You can either reverse your use of single and double quotes (encoded URLs cannot contain double quotes, but they can contain single quotes) or replace the single quotes in the URL with a character entity like '
. URL encoding by %27
would also work, but that's not a standard encoding that encodeURIComponent
does.