diff --git a/snippets/escapeHTML.md b/snippets/escapeHTML.md new file mode 100644 index 000000000..7ca23af6d --- /dev/null +++ b/snippets/escapeHTML.md @@ -0,0 +1,19 @@ +### escapeHTML + +Escapes a string for use in HTML. + +Use `String.replace()` with a regex that matches the characters that need to be escaped, using a callback function to replace each character instance with its associated escaped character using a dictionary (object). + +```js +const escapeHTML = str => str.replace(/[&<>'"]/g, tag => ({ + '&': '&', + '<': '<', + '>': '>', + '\'': ''', + '"': '"' + })[tag] || tag); +``` + +```js +escapeHTML('Me & you'); // '<a href="#">Me & you</a>' +``` diff --git a/snippets/unescapeHTML.md b/snippets/unescapeHTML.md new file mode 100644 index 000000000..3325e1400 --- /dev/null +++ b/snippets/unescapeHTML.md @@ -0,0 +1,17 @@ +### unescapeHTML + +Unescapes escaped HTML characters. + +Use `String.replace()` with a regex that matches the characters that need to be escaped, using a callback function to replace each escaped character instance with its associated unescaped character using a dictionary (object). + +```js +const unescapeHTML = str => str.replace(/&|<|>|'|"/g, tag => ({ + '&': '&', + '<': '<', + '>': '>', + ''': '\'', + '"': '"' + })[tag] || tag);``` +```js +unescapeHTML('<a href="#">Me & you</a>'); // 'Me & you' +``` diff --git a/tag_database b/tag_database index c828836c8..604d1d876 100644 --- a/tag_database +++ b/tag_database @@ -30,6 +30,7 @@ dropElements:array dropRight:array elementIsVisibleInViewport:browser escapeRegExp:string +escapeHTML:string everyNth:array extendHex:utility factorial:math @@ -137,6 +138,7 @@ toOrdinalSuffix:utility toSnakeCase:string truncateString:string truthCheckCollection:object +unescapeHTML:string union:array UUIDGeneratorBrowser:browser UUIDGeneratorNode:node