From edc437636629790dc8cdd46fa1233a0faa828b63 Mon Sep 17 00:00:00 2001 From: atomiks Date: Sat, 30 Dec 2017 00:08:16 +1100 Subject: [PATCH] Update unescapeString.md --- snippets/unescapeString.md | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/snippets/unescapeString.md b/snippets/unescapeString.md index 5e6e14a01..8408fc744 100644 --- a/snippets/unescapeString.md +++ b/snippets/unescapeString.md @@ -1,14 +1,17 @@ -### unescapeString +### unescapeHTML -Unescapes a string from HTML. +Unescapes escaped HTML characters. -Use a chain of `String.replace()` calls combined with regular expressions to replace special characters with the proper symbols. +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 unescapeString = str => - str.replace(/>/g, '>').replace(/</g, '<').replace(/'/g, '\'').replace(/"/g, '"').replace(/&/g, '&'); -``` - +const escapeHTML = str => str.replace(/[&<>'"]/g, tag => ({ + '&': '&', + '<': '<', + '>': '>', + ''': '\'', + '"': '"' + })[tag] || tag);``` ```js -unescapeString('<a href="#">Me & you</a>'); // 'Me & you' +unescapeHTML('<a href="#">Me & you</a>'); // 'Me & you' ```