Consolidate escape and unescape modules.

This commit is contained in:
John-David Dalton
2017-01-10 17:09:40 -08:00
parent fc1a360212
commit c5d4bb8dcb
4 changed files with 20 additions and 46 deletions

View File

@@ -1,21 +0,0 @@
import basePropertyOf from './.internal/basePropertyOf.js';
/** Used to map characters to HTML entities. */
const htmlEscapes = {
'&': '&',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;'
};
/**
* Used by `escape` to convert characters to HTML entities.
*
* @private
* @param {string} chr The matched character to escape.
* @returns {string} Returns the escaped character.
*/
const escapeHtmlChar = basePropertyOf(htmlEscapes);
export default escapeHtmlChar;

View File

@@ -1,21 +0,0 @@
import basePropertyOf from './.internal/basePropertyOf.js';
/** Used to map HTML entities to characters. */
const htmlUnescapes = {
'&amp;': '&',
'&lt;': '<',
'&gt;': '>',
'&quot;': '"',
'&#39;': "'"
};
/**
* Used by `unescape` to convert HTML entities to characters.
*
* @private
* @param {string} chr The matched character to unescape.
* @returns {string} Returns the unescaped character.
*/
const unescapeHtmlChar = basePropertyOf(htmlUnescapes);
export default unescapeHtmlChar;

View File

@@ -1,6 +1,14 @@
import escapeHtmlChar from './.internal/escapeHtmlChar.js';
import toString from './toString.js';
/** Used to map characters to HTML entities. */
const htmlEscapes = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;'
};
/** Used to match HTML entities and HTML characters. */
const reUnescapedHtml = /[&<>"']/g;
const reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
@@ -34,7 +42,7 @@ const reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
function escape(string) {
string = toString(string);
return (string && reHasUnescapedHtml.test(string))
? string.replace(reUnescapedHtml, escapeHtmlChar)
? string.replace(reUnescapedHtml, chr => htmlEscapes[chr])
: string;
}

View File

@@ -1,5 +1,13 @@
import toString from './toString.js';
import unescapeHtmlChar from './.internal/unescapeHtmlChar.js';
/** Used to map HTML entities to characters. */
const htmlUnescapes = {
'&amp;': '&',
'&lt;': '<',
'&gt;': '>',
'&quot;': '"',
'&#39;': "'"
};
/** Used to match HTML entities and HTML characters. */
const reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g;
@@ -25,7 +33,7 @@ const reHasEscapedHtml = RegExp(reEscapedHtml.source);
function unescape(string) {
string = toString(string);
return (string && reHasEscapedHtml.test(string))
? string.replace(reEscapedHtml, unescapeHtmlChar)
? string.replace(reEscapedHtml, entity => htmlUnescapes[entity])
: string;
}