Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
9ec9ce8
commit 0a96fd7
Showing
7 changed files
with
353 additions
and
19 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
import entities from './entities.json' | ||
|
||
const HTMLEntityRe = /&(\S+);/g | ||
const HEX_NUMBER = /^[\da-fA-F]+$/ | ||
const DECIMAL_NUMBER = /^\d+$/ | ||
|
||
/** | ||
* Encode unicode hex html entities like for example Ȣ | ||
* @param {string} string - input string | ||
* @returns {string} encoded string | ||
*/ | ||
export function encodeHex(string) { | ||
const hex = string.substr(2) | ||
|
||
return HEX_NUMBER.test(hex) ? | ||
String.fromCodePoint(parseInt(hex, 16)) : | ||
string | ||
} | ||
|
||
/** | ||
* Encode unicode decimal html entities like for example Þ | ||
* @param {string} string - input string | ||
* @returns {string} encoded string | ||
*/ | ||
export function encodeDecimal(string) { | ||
const nr = string.substr(1) | ||
|
||
return DECIMAL_NUMBER.test(nr) ? | ||
String.fromCodePoint(parseInt(nr, 10)) | ||
: string | ||
} | ||
|
||
/** | ||
* Encode html entities in strings like | ||
* @param {string} string - input string | ||
* @returns {string} encoded string | ||
*/ | ||
export default function encodeHTMLEntities(string) { | ||
return string.replace(HTMLEntityRe, (match, entity) => { | ||
const [firstChar, secondChar] = entity | ||
|
||
if (firstChar === '#') { | ||
return secondChar === 'x' ? | ||
encodeHex(entity) : | ||
encodeDecimal(entity) | ||
} else { | ||
return entities[entity] || entity | ||
} | ||
}) | ||
} |
Oops, something went wrong.