When emitting react code, replace HTML numeric entities with their encoded characters

This commit is contained in:
Andy Hanson 2016-09-07 06:34:28 -07:00
parent 874846a534
commit eea03801e0
5 changed files with 23 additions and 5 deletions

View file

@ -210,15 +210,21 @@ namespace ts {
}
/**
* Decodes JSX entities.
* Replace entities like " ", "{", and "�" with the characters they encode.
* See https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references
*/
function decodeEntities(text: string) {
return text.replace(/&(\w+);/g, function(s: any, m: string) {
if (entities[m] !== undefined) {
return String.fromCharCode(entities[m]);
return text.replace(/&((#((\d+)|x([\da-fA-F]+)))|(\w+));/g, (match, _all, _number, _digits, decimal, hex, word) => {
if (decimal) {
return String.fromCharCode(parseInt(decimal, 10));
}
else if (hex) {
return String.fromCharCode(parseInt(hex, 16));
}
else {
return s;
const ch = entities[word];
// If this is not a valid entity, then just use `match` (replace it with itself, i.e. don't replace)
return ch ? String.fromCharCode(ch) : match;
}
});
}

View file

@ -9,8 +9,10 @@ declare var React: any;
<div>Dot goes here: &middot; &notAnEntity; </div>;
<div>Be careful of &quot;-ed strings!</div>;
<div>&#0123;&#123;braces&#x7d;&#x7D;</div>;
//// [file.js]
React.createElement("div", null, "Dot goes here: \u00B7 &notAnEntity; ");
React.createElement("div", null, "Be careful of \"-ed strings!");
React.createElement("div", null, "{{braces}}");

View file

@ -23,3 +23,7 @@ declare var React: any;
>div : Symbol(JSX.IntrinsicElements, Decl(file.tsx, 1, 22))
>div : Symbol(JSX.IntrinsicElements, Decl(file.tsx, 1, 22))
<div>&#0123;&#123;braces&#x7d;&#x7D;</div>;
>div : Symbol(JSX.IntrinsicElements, Decl(file.tsx, 1, 22))
>div : Symbol(JSX.IntrinsicElements, Decl(file.tsx, 1, 22))

View file

@ -25,3 +25,8 @@ declare var React: any;
>div : any
>div : any
<div>&#0123;&#123;braces&#x7d;&#x7D;</div>;
><div>&#0123;&#123;braces&#x7d;&#x7D;</div> : JSX.Element
>div : any
>div : any

View file

@ -10,3 +10,4 @@ declare var React: any;
<div>Dot goes here: &middot; &notAnEntity; </div>;
<div>Be careful of &quot;-ed strings!</div>;
<div>&#0123;&#123;braces&#x7d;&#x7D;</div>;