简体   繁体   中英

Converting Unicode Escape Sequence to Symbol, and dumping to dom node

Browser: FF Latest / Chrome Latest
jQuery: 1.x edge

An ajax request produces this response (sent as plain text, single line, valid JSON (produced by Gson) handled by jQuery as plain text).

{
  "fromSymbol": "\\u04b0",
  "toCurrency": "AUD",
  "toSymbol": "\\u0024",
  "convFactorPrecise": 0.171346,
  "amount": 38020.0,
  "convertedAmountPrecise": 6514.57,
  "convertedAmountFormatted": "6,514.57"
}

(Formatted here for easy reading, but it arrives as single line, minified).

Then I use the following line to convert the plain text into an object literal:

var currObj = $.parseJSON($.trim(thatStringUpThere));

The problem is, currObj.toSymbol is now literally '\$', and not '$'.

  • Consider that I cannot change the response type and handle as json
  • And given that I only have that plain string to work with in jQuery's success method

Q: how would I dump $ into a dom node?

(Currently, jquery's .html() and .text() keep dumping '\$' to the dom, and not the $ symbol).

Thanks.

Simple solution:

unescape(JSON.parse($.trim(thatStringUpThere)));

More elegant solution:

var r = /\\u([\d\w]{4})/gi; 
x = unescape (x.replace(r, function (match, grp) { 
  return String.fromCharCode(parseInt(grp, 16)); 
} ));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM