SSeybold
SSeybold

Reputation: 39

Write HTML Special Character into a Variable

$("<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("&#176;") + 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

Answers (3)

Marcel
Marcel

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: $('&lt;div/&gt;').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

Sami Almalki
Sami Almalki

Reputation: 628

Special characters are characters that must be escaped by a backslash\, like:

  • Single quote \'
  • Double quote \"
  • Backslash \\

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

SOUPaLOOP
SOUPaLOOP

Reputation: 121

Escape Special Characters JavaScript

JavaScript uses the \ (backslash) as an escape characters for:

  • \' single quote
  • \" double quote
  • \ backslash
  • \n new line
  • \r carriage return
  • \t tab
  • \b backspace
  • \f form feed
  • \v vertical tab (IE < 9 treats '\v' as 'v' instead of a vertical tab ('\x0B').
  • If cross-browser compatibility is a concern, use \x0B instead of \v.) \0 null character (U+0000 NULL) (only if the next character is not a decimal digit; else it’s an octal escape sequence)

Note that the \v and \0 escapes are not allowed in JSON strings.

Upvotes: 0

Related Questions