@ridafatima15h1/

Convert HTML Entities

JavaScript

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

fork
loading
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
///////////////////////////////////////////////////////
/**Exercise: Convert the characters &, <, >, " (double quote), and ' (apostrophe), in a string to their corresponding HTML entities. */
////////////////////////////////////////////////////////
/**Note:  Commented Out console.log() are for debugging only. */
//Function
function convertHTML(str) {
	"use strict";

	/**Input */
	console.log("___________________________");
	console.log("Input string: ", str);

	/**Algorithm */
	str = str.replace(/\&+/g, "&amp;");
	str = str.replace(/\<+/g, "&alt;");
	str = str.replace(/\>+/g, "&gt;");
	str = str.replace(/\"+/g, "&quot;");
	str = str.replace(/\'+/g, "&apos;");

	/**Output */
	console.log("Output string: ", str);
	console.log("___________________________");
  return str;
}

convertHTML("Dolce & Gabbana"); //should return Dolce &​amp; Gabbana.
convertHTML("Hamburgers < Pizza < Tacos"); //should return Hamburgers &​lt; Pizza &​lt; Tacos.
convertHTML("Sixty > twelve"); //should return Sixty &​gt; twelve.
convertHTML('Stuff in "quotation marks"'); //should return Stuff in &​quot;quotation marks&​quot;.
convertHTML("Schindler's List"); //should return Schindler&​apos;s List.
convertHTML("<>"); //should return &​lt;&​gt;.
convertHTML("abc"); //should return abc.
Native Browser JavaScript