HOW TO handle quotes within injected text assigned to Title attribute of a HTML element
While working with the YouTube API, I needed to populate the value of a anchor's title attribute with text generated dynamically from YouTube's JSON API
On inspecting the HTML source code of a rendered page, I noticed that if the title had double quotes it would disturb the double quotes that it is already enclosed within. I used this custom function to fix it
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Before: | |
elem.append('<a title="'results[i].title | |
+ '" href="http://www.youtube.com/embed/' + results[i].id + '?autoplay=1&vq=small&autohide=2&iv_load_policy=3" >' + results[i].title + '</a>'); | |
function htmlEscape(str) { | |
return String(str) | |
.replace(/'/g, ''') | |
.replace(/"/g, '"'); | |
} | |
After: | |
elem.append('<a title="'htmlEscape(results[i].title) | |
+ '" href="http://www.youtube.com/embed/' + results[i].id + '?autoplay=1&vq=small&autohide=2&iv_load_policy=3" >' + results[i].title + '</a>'); |
Comments
Post a Comment