-
Notifications
You must be signed in to change notification settings - Fork 0
/
alg11-convertHTMLEntities.js
98 lines (90 loc) · 2.85 KB
/
alg11-convertHTMLEntities.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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
const assert = require('assert');
/*
Source: <https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/convert-html-entities>
Convert HTML Entities
Convert the characters &, <, >, " (double quote), and ' (apostrophe), in a string to their corresponding HTML entities.
*/
function myConvertHTML(str) {
/* return str.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
*/
const HTMLEntities = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
}
const HTMLEntitiesKeys = Object.keys(HTMLEntities);
const fetchHTMLEntities = (char) => HTMLEntitiesKeys.includes(char) ? char = HTMLEntities[char] : char;
return str.split('').map(fetchHTMLEntities).join('');
}
assert.strictEqual(myConvertHTML('Dolce & Gabbana'), 'Dolce & Gabbana');
assert.strictEqual(myConvertHTML('Hamburgers < Pizza < Tacos'), 'Hamburgers < Pizza < Tacos');
assert.strictEqual(myConvertHTML('Sixty > twelve'), 'Sixty > twelve');
assert.strictEqual(myConvertHTML('Stuff in "quotation marks"'), 'Stuff in "quotation marks"');
assert.strictEqual(myConvertHTML(`Schindler's List`), 'Schindler's List');
assert.strictEqual(myConvertHTML('<>'), '<>');
assert.strictEqual(myConvertHTML('abc'), 'abc');
/*
Get a help > Get a hint <https://forum.freecodecamp.org/t/freecodecamp-challenge-guide-convert-html-entities/16007>
*/
//Solution 1
function convertHTML1(str) {
// Split by character to avoid problems.
var temp = str.split("");
// Since we are only checking for a few HTML elements, use a switch
for (var i = 0; i < temp.length; i++) {
switch (temp[i]) {
case "<":
temp[i] = "<";
break;
case "&":
temp[i] = "&";
break;
case ">":
temp[i] = ">";
break;
case '"':
temp[i] = """;
break;
case "'":
temp[i] = "'";
break;
}
}
temp = temp.join("");
return temp;
}
//Solution 2
function convertHTML2(str) {
// Use Object Lookup to declare as many HTML entities as needed.
const htmlEntities = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'"
};
// Using a regex, replace characters with it's corresponding html entity
return str.replace(/([&<>\"'])/g, match => htmlEntities[match]);
}
//Solution 3
function convertHTML3(str) {
// Use Object Lookup to declare as many HTML entities as needed.
const htmlEntities = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'"
};
//Use map function to return a filtered str with all entities changed automatically.
return str
.split("")
.map(entity => htmlEntities[entity] || entity)
.join("");
}