feat(curriculum): Extend solution explanation for Convert HTML Entities challenge (#35835)

* Extend solution explanation

The explanation for the advanced code solution was a little cumbersome.
It tried to explain the used method, but also tried to explain an alternative solution, both mixed together.
To fix that, I moved everything related to the alternative solution to another paragraph.
Additionally, I added a more detailed explanation about this alternative solution.
Hopefully, with this fixes, both solutions will be clearer to the user.

* Replace intermediate solution

Replace the intermediate solution with a more concise one.

I took the opportunity to eliminate the indenting in all 3 snippets to remove unnecessary blank space on the left.
I also changed the wording on one of the instructions and fixed a typo.

* Remove external links

* Simplity regex declaration

I replaced `new RegExp()` in order to make the solution cleaner and shorter

* Update index.md
This commit is contained in:
Guayo Mena
2019-05-26 13:23:41 +01:00
committed by Parth Parth
parent e6dbbe08d8
commit f5b94b51f1

View File

@ -1,6 +1,9 @@
--- ---
title: Convert HTML Entities title: Convert HTML Entities
--- ---
# Convert HTML Entities
![HTML entities &'<>"](//discourse-user-assets.s3.amazonaws.com/original/2X/f/fc44d1dfbd3910e574cdedb0f05162f65b4cb7c4.jpg) ![HTML entities &'<>"](//discourse-user-assets.s3.amazonaws.com/original/2X/f/fc44d1dfbd3910e574cdedb0f05162f65b4cb7c4.jpg)
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:") ![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
@ -35,39 +38,39 @@ title: Convert HTML Entities
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution: ## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
```javascript ```javascript
function convertHTML(str) { function convertHTML(str) {
// Split by character to avoid problems. // Split by character to avoid problems.
var temp = str.split(''); var temp = str.split('');
// Since we are only checking for a few HTML elements I used a switch // Since we are only checking for a few HTML elements, use a switch
for (var i = 0; i < temp.length; i++) { for (var i = 0; i < temp.length; i++) {
switch (temp[i]) { switch (temp[i]) {
case '<': case '<':
temp[i] = '&lt;'; temp[i] = '&lt;';
break; break;
case '&': case '&':
temp[i] = '&amp;'; temp[i] = '&amp;';
break; break;
case '>': case '>':
temp[i] = '&gt;'; temp[i] = '&gt;';
break; break;
case '"': case '"':
temp[i] = '&quot;'; temp[i] = '&quot;';
break; break;
case "'": case "'":
temp[i] = "&apos;"; temp[i] = "&apos;";
break; break;
}
}
temp = temp.join('');
return temp;
} }
}
//test here temp = temp.join('');
convertHTML("Dolce & Gabbana"); return temp;
}
//test here
convertHTML("Dolce & Gabbana");
``` ```
### Code Explanation: ### Code Explanation:
@ -82,27 +85,31 @@ title: Convert HTML Entities
* <a href='https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/join' target='_blank' rel='nofollow'>arr.join()</a> * <a href='https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/join' target='_blank' rel='nofollow'>arr.join()</a>
* <a href='https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/switch' target='_blank' rel='nofollow'>switch statement</a> * <a href='https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/switch' target='_blank' rel='nofollow'>switch statement</a>
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLnP/0' target='_blank' rel='nofollow'>Run Code</a>
## ![:sunflower:](https://forum.freecodecamp.com/images/emoji/emoji_one/sunflower.png?v=3 ":sunflower:") Intermediate Code Solution: ## ![:sunflower:](https://forum.freecodecamp.com/images/emoji/emoji_one/sunflower.png?v=3 ":sunflower:") Intermediate Code Solution:
function convertHTML(str) { ```javascript
//Chaining of replace method with different arguments function convertHTML(str) {
str = str.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,"&apos;"); // Use Object Lookup to declare as many HTML entities as needed.
return str; const htmlEntities = {
} "&" : '&amp;',
"<" : "&lt;",
">" : "&gt;",
'"' : "&quot;",
"'" :"&apos;"
}
// Using a regex, replace characters with it's corresponding html entity
return str.replace(/([&<>\"'])/g, match => htmlEntities[match]);
}
// test here // test here
convertHTML("Dolce & Gabbana"); convertHTML("Dolce & Gabbana");
```
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLnQ/0' target='_blank' rel='nofollow'>Run Code</a>
### Code Explanation: ### Code Explanation:
* Create an object to use the Lookup functionality and easily find the characters.
* **str** is assigned to a new version of **str** that will contain the original string with all HTML entities converted * Use `replace()` to replace characters with regex.
* The **first parameters** in `replace()` contains a regular expression that matches all instances of each HTML entity in **str** * The first argument for `replace()` is a regex that catches all the target characters and puts them into a capturing group.
* Replace all those instances with the corresponding HTML strings given in the **second parameter** of `replace()` * The second arguments for `replace()` is a function with the matched character as a parameter. It returns the correspondant entity from `htmlEntities`.
* Finally, the new **str** is returned
#### Relevant Links #### Relevant Links
@ -110,30 +117,30 @@ title: Convert HTML Entities
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp' target='_blank' rel='nofollow'>Regular Expressions</a> * <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp' target='_blank' rel='nofollow'>Regular Expressions</a>
## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ":rotating_light:") Advanced Code Solution: ## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ":rotating_light:") Advanced Code Solution:
```javascript
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('');
}
// test here ```javascript
convertHTML("Dolce & Gabbana"); 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('');
}
// test here
convertHTML("Dolce & Gabbana");
``` ```
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLnR/0' target='_blank' rel='nofollow'>Run Code</a>
### Code Explanation: ### Code Explanation:
* Create a object to use the Lookup functionality to easily find the characters. * Create an object to use the Lookup functionality and easily find the characters.
* Split the original string by characters and use map to check for the changed html entity or use the same one. Alternatively you could use Regex `str.replace(/&|<|>|"|'/gi`. * Split the original string by characters and use map to check for the changed html entity or use the same one.
* The a function is added which is what returns the converted entity or the original one if there is no conversion. If you go the regex route then you just have to return the matched hits. `return html[entity];` * The a function is added which is what returns the converted entity or the original one if there is no conversion.
* Lastly we join all the characters once again. * Lastly we join all the characters once again.
**Note** that if you went the regex route then you don't need to join anything, just make sure you return the whole operation or save it to a variable and then return it. **Note** that if you went the regex route then you don't need to join anything, just make sure you return the whole operation or save it to a variable and then return it.