Skip to content

Commit 9393c75

Browse files
committed
Complete convert HTML entities algorithm
1 parent e9f00e0 commit 9393c75

File tree

3 files changed

+61
-0
lines changed

3 files changed

+61
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
export function convertHTML(str) {
2+
const getEscapedString = function(char) {
3+
switch (char) {
4+
case '>':
5+
return '>';
6+
case '&':
7+
return '&';
8+
case '<':
9+
return '&lt;';
10+
case '\'':
11+
return '&apos;';
12+
case '\"':
13+
return '&quot;';
14+
default:
15+
return char;
16+
}
17+
}
18+
let newString = [];
19+
for (let char of str) {
20+
newString.push(getEscapedString(char));
21+
}
22+
23+
return newString.join('');
24+
}

src/fcc-intermediate-algorithms/fcc-intermediate-algorithms.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ From the Freecodecamp Javascript Certification Intermediate Algorithms module
1414
- [DNA Pairing](#dna-pairing)
1515
- [Missing Letters](#missing-letters)
1616
- [Sorted Union](#sorted-union)
17+
- [Convert HTML Entities](#convert-html-entities)
1718

1819
#### Sum All Numbers In a Range
1920

@@ -220,3 +221,34 @@ export function uniteUnique(...arr) {
220221
}, []);
221222
}
222223
```
224+
225+
#### Convert HTML Entities
226+
227+
Convert the characters &, <, >, " (double quote), and ' (apostrophe), in a string to their corresponding HTML entities.
228+
229+
```javascript
230+
export function convertHTML(str) {
231+
const getEscapedString = function(char) {
232+
switch (char) {
233+
case '>':
234+
return '&gt;';
235+
case '&':
236+
return '&amp;';
237+
case '<':
238+
return '&lt;';
239+
case '\'':
240+
return '&apos;';
241+
case '\"':
242+
return '&quot;';
243+
default:
244+
return char;
245+
}
246+
}
247+
let newString = [];
248+
for (let char of str) {
249+
newString.push(getEscapedString(char));
250+
}
251+
252+
return newString.join('');
253+
}
254+
```
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import { convertHTML } from "../../src/fcc-intermediate-algorithms/convert_html_entities";
2+
3+
test('should convert HTML entities', () => {
4+
expect(convertHTML("Dolce & Gabbana")).toBe("Dolce &amp; Gabbana");
5+
});

0 commit comments

Comments
 (0)