3

I am adding CSS styles using JavaScript (specifically with GreaseMonkey's GM_addStyle).

I'd like to put a Unicode character in a CSS property. I've seen a lot of questions like this one and the answer always seems to be along the lines of

#target:before {
    content: "\2611";
}

Now, as I said, this style is being specified in GM_addStyle, and the calling function has Strict mode enabled. When my script runs, I get an error on the console with the message octal literals and octal escape sequences are deprecated.

I think the conflict here is between doing the operation in JavaScript (i.e. putting a Unicode character into a JavaScript string) and the operation in CSS (escaping the character when declaring a CSS property). What syntax should I use to have the character escaped without generating an error?

Community
  • 1
  • 1
Coderer
  • 25,844
  • 28
  • 99
  • 154
  • 1
    Your question is confusing - are you referring to JavaScript, or CSS, or both? As far as I know, escape sequences in CSS have never been deprecated by any specification. – BoltClock Jun 16 '14 at 10:19
  • I think my confusion was the root issue. I'm adding CSS style definitions with `GM_addStyle`; under the hood I think this is effectively writing new ` – Coderer Jun 16 '14 at 10:39
  • CSS never had “octal escape sequences”. There is real problem involved here, but it seems to be related to JavaScript, not to CSS at all. I’m afraid it has been expressed so confusingly that the question will hardly be useful to future visitors. – Jukka K. Korpela Jun 16 '14 at 11:08
  • I think you are right, Jukka; I will add a postscript to try to clarify. – Coderer Jun 16 '14 at 14:18
  • Also, in case anybody missed it in my comment below, I wanted to raise the visibility of [this article on JavaScript string escapes](http://mathiasbynens.be/notes/javascript-escapes) which really helped to straighten me out. – Coderer Jun 16 '14 at 14:25

1 Answers1

4

I'm trying to do just this in GreaseMonkey, with Strict mode enabled.

If you're going via JavaScript, then the String '\2611' doesn't have the same meaning as you think it does and you probably want the String '\u2611' or '\\2611'

'\2611';  // "±1"
'\u2611'; // "☑"
'\\2611'; // "\2611"
Paul S.
  • 64,864
  • 9
  • 122
  • 138
  • FWIW, the first is equivalent to `\u00b11`, i.e. the Unicode character `00b1` and a `"1"` – lc. Jun 16 '14 at 10:22
  • @lc. yep, for anyone interested in how to convert the first output as it's not a simple oct -> hex `'\261'.charCodeAt(0).toString(16); // "b1"` then make this 4 digits long by prepending `"0"`s – Paul S. Jun 16 '14 at 10:25
  • 1
    While you were posting this, I was reading [an excellent article](http://mathiasbynens.be/notes/javascript-escapes) that explained the difference. It makes a lot more sense now. Thanks! – Coderer Jun 16 '14 at 10:37