Skip to content

Instantly share code, notes, and snippets.

@martin-mok
Last active January 11, 2020 23:34
Show Gist options
  • Select an option

  • Save martin-mok/17fff0fed95f940c946180c2deca6a0d to your computer and use it in GitHub Desktop.

Select an option

Save martin-mok/17fff0fed95f940c946180c2deca6a0d to your computer and use it in GitHub Desktop.
freecodecamp: Convert HTML Entities

Description

Convert the characters &, <, >, " (double quote), and ' (apostrophe), in a string to their corresponding HTML entities.

Tests

tests:
  - text: <code>convertHTML("Dolce & Gabbana")</code> should return <code>Dolce &amp;amp; Gabbana</code>.
    testString: assert.match(convertHTML("Dolce & Gabbana"), /Dolce &amp; Gabbana/);
  - text: <code>convertHTML("Hamburgers < Pizza < Tacos")</code> should return <code>Hamburgers &amp;lt; Pizza &amp;lt; Tacos</code>.
    testString: assert.match(convertHTML("Hamburgers < Pizza < Tacos"), /Hamburgers &lt; Pizza &lt; Tacos/);
  - text: <code>convertHTML("Sixty > twelve")</code> should return <code>Sixty &amp;gt; twelve</code>.
    testString: assert.match(convertHTML("Sixty > twelve"), /Sixty &gt; twelve/);
  - text: <code>convertHTML(&apos;Stuff in "quotation marks"&apos;)</code> should return <code>Stuff in &amp;quot;quotation marks&amp;quot;</code>.
    testString: assert.match(convertHTML('Stuff in "quotation marks"'), /Stuff in &quot;quotation marks&quot;/);
  - text: <code>convertHTML("Schindler&apos;s List")</code> should return <code>Schindler&amp;apos;s List</code>.
    testString: assert.match(convertHTML("Schindler's List"), /Schindler&apos;s List/);
  - text: <code>convertHTML("<>")</code> should return <code>&amp;lt;&amp;gt;</code>.
    testString: assert.match(convertHTML('<>'), /&lt;&gt;/);
  - text: <code>convertHTML("abc")</code> should return <code>abc</code>.
    testString: assert.strictEqual(convertHTML('abc'), 'abc');

Solution

Offical soln:

var MAP = { '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&apos;'};

function convertHTML(str) {
  return str.replace(/[&<>"']/g, function(c) {
    return MAP[c];
  });
}

without regex:
freeCodeCamp Challenge Guide: Convert HTML Entities

function convertHTML(str) {
  // Use Object Lookup to declare as many HTML entities as needed.
  const htmlEntities = {
    "&": "&amp;",
    "<": "&lt;",
    ">": "&gt;",
    '"': "&quot;",
    "'": "&apos;"
  };
  //Use map function to return a filtered str with all entities changed automatically.
  return str
    .split("")
    .map(entity => htmlEntities[entity] || entity)
    .join("");
}

Other solns may involve the creation of DOM object.
JavaScript HTML Entities Encode & Decode
Decoding HTML entities with vanilla JavaScript

var decodeHTML = function (html) {
	var txt = document.createElement('textarea');
	txt.innerHTML = html;
	return txt.value;
};

// Example
// Returns "<p>In this course, you'll learn:</p>"
var decoded = decodeHTML('&lt;p&gt;In this course, you&rsquo;ll learn:&lt;/p&gt;');

It works by creating a <textarea> element and injecting your encoded HTML into it.
The browser automatically converts that back into proper HTML.
You can then grab the value from the <textarea>, and like magic, you have decided HTML.

JavaScript: How to decode an encode HTML-entities
htmlEntities for JavaScript
htmlentities() is a PHP function which converts special characters (like <) into their escaped/encoded values (like <).
JavaScript doesn't have a native version of it.
stackoverflow:

  1. HTML Entity Decode
  2. What's the right way to decode a string that has special HTML entities in it?

Encode and Decode HTML entities using pure Javascript

(function(window){
	window.htmlentities = {
		/**
		 * Converts a string to its html characters completely.
		 *
		 * @param {String} str String with unescaped HTML characters
		 **/
		encode : function(str) {
			var buf = [];
			
			for (var i=str.length-1;i>=0;i--) {
				buf.unshift(['&#', str[i].charCodeAt(), ';'].join(''));
			}
			
			return buf.join('');
		},
		/**
		 * Converts an html characterSet into its original character.
		 *
		 * @param {String} str htmlSet entities
		 **/
		decode : function(str) {
			return str.replace(/&#(\d+);/g, function(match, dec) {
				return String.fromCharCode(dec);
			});
		}
	};
})(window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment