Reputation: 39
$("<h2/>", {"class" : "wi wi"+data.today.code}).text(" " + data.city + data.today.temp.now + "F").appendTo(custom_example);
Hi there, I'm trying to alter the code above to add the degrees icon just before the (F)arenheit marker. I've tried entering + html("°") +
but it doesn't work. My JS is pretty rough and I was hoping I could get a quick answer here before I spent too long trying and failing. Thanks!
I want the end result to print something like: Encinitas 65°F
Upvotes: 0
Views: 2788
Reputation: 1840
First of all the degree character needs not to be escaped. So simply entering "°F"
should do the job.
However, if you are in doubt with the codepage of your JS code you could use a JavaScript escape sequence. JS escape sequences are quite different from HTML escapes. The do not support decimal values at all. So first of all you have to convert 176
to hex: b0
. The correctly escaped equivalent to "°F"
is "\xb0F"
. It will work too and is more robust with respect to codepage issues of you platform's source editor.
If you really want to assign HTML code you need to use the .html()
function. But this is mutual exclusive to .text()
. So in this case all of your content needs to be HTML rather than plain text. Otherwise an HTML injection vulnerability arises. I.e. you need to properly escape angle brackets and some other symbols in data.city
and maybe data.today.temp.now
as well.
JS itself has no built-in function to escape HTML. But JQuery provides a trick: $('<div/>').text(data.city).html()
will return appropriately escaped HTML. See HTML-encoding lost when attribute read from input field for more details.
I would recommend not to use .html()
unless you really need it, e.g. if you want to apply styles or formatting to parts of the text only.
Upvotes: 0
Reputation: 628
Special characters are characters that must be escaped by a backslash\
, like:
\'
\"
\\
The degree ° is not a special character, you can just write it, as it is.
Edit: If you want to use the unicode
of °F, just write: '\u2109'
.
Upvotes: 6
Reputation: 121
Escape Special Characters JavaScript
JavaScript uses the \ (backslash) as an escape characters for:
Note that the \v and \0 escapes are not allowed in JSON strings.
Upvotes: 0