Convert HTML Entities

Learn how to solve the freeCodeCamp algorithm 'Convert HTML Entities' using the String.split(), Array.map(), Array.splice(), and Array.join methods!

Convert HTML Entities

In this freeCodeCamp algorithm we will convert certain characters, such as &, <, >, ", and ' into their corresponding HTML entities. For example, the HTML entity for & would be &.

Requirements

  • 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

Real-World Use Cases

Character encoding is necessary for security purposes as it otherwise would leave webpages and applications susceptible to Cross-Site Scripting attacks.

See here for more information:

Cross-Site Scripting (XSS) attacks are a type of injection, in which malicious scripts are injected into otherwise benign and trusted websites. XSS attacks occur when an attacker uses a web application to send malicious code, generally in the form of a browser side script, to a different end user. Flaws that allow these attacks to succeed are quite widespread and occur anywhere a web application uses input from a user within the output it generates without validating or encoding it.

Psuedocode

Let's walkthrough the problem we're trying to solve, step-by-step, using plain English:


// Create a function that accepts a string
    
    // Split up the string into an array individual characters
    
    // Loop through the array checking if for special characters
    
        // If there's a match, convert the special character to its corresponding HTML entity
        
    // Join the array of characters back into a single string and return it

Solving the Algorithm

Setting up our function

Let's use the boilerplate function provided to us from freeCodeCamp:

function convertHTML(str) {
  // &colon;&rpar;
  return str;
}

convertHTML("Dolce & Gabbana");

Convert the string into an array of individual characters

Here we can use the String.split() method which accepts an optional separator argument. The separator denotes at what point the string should be split, so in our case we want to split the string at each character. To do so, we must pass in an empty string as the separator argument ("").

From the String.split() MDN Docs:

If separator is an empty string, str is converted to an array of characters.

Let's implement the String.split() method into our code. Let's also make sure we return the new variable, strArr instead of returning str which came from the freeCodeCamp boilerplate function.

function convertHTML(str) {
  // &colon;&rpar;

  let strArr = str.split('');

  return strArr;
}

convertHTML("Dolce & Gabbana");

Map over the array

Now that we have str divided up into an array of individual characters we can use the Array.map() method which will return a new array from the resulting function that's ran on every element passed into it.

Array.map() is one of the most useful array methods available to us in the JavaScript language so if you'd like to read more about it, click here.

Array.map accepts a callback function as an argument which contains the currentValue paremeter along with an optional index and array parameter.

In our case, we will pass in a callback function that sets the currentValue parameter to be char. We we also utilize the index parameter. We will refer to it as i.

function convertHTML(str) {
  // &colon;&rpar;

  let strArr = str.split('')

  strArr.map((char, i) => {
  
	// Create logic to check for special characters
    
  })

  return strArr.join('');
}

convertHTML("Dolce & Gabbana");

Check for special characters

Now that we're able to map over each item in our array of individual characters, we can setup our logic. If you recall, our logic will need to check if the current item in the array is one of the special characters (&, <, >, ", or '), and if there's a match, it needs to replace the special character with its corresponding HTML entity.

Here's a list of HTML character entities

Ok, so let's write some logic that will check if the current item in the array is a special character, and if so - replace it. We can use the Array.splice() method to replace the current value with the desired value.

function convertHTML(str) {
  // &colon;&rpar;

  let strArr = str.split('')

  strArr.map((char, i) => {
	if (char == "&") {
		strArr.splice(i, 1, "&amp;")
	} 
	if (char == "<"){
		strArr.splice(i, 1, "&lt;")
	}
	if (char == ">"){
		strArr.splice(i, 1, "&gt;")
	}
	if (char == "\""){
		strArr.splice(i, 1, "&quot;")
	}
	if (char == "'"){
		strArr.splice(i, 1, "&apos;")
	}
     
  })

  return strArr;
}

convertHTML("Dolce & Gabbana");

Join the array of individual characters back to a complete string

At this point, we've setup our algorithm to do everything we want. The only catch is that when we return strArr it still returns an array of individual characters like this: ["D", "o", "l", "c", "e", " ", "&", " ", "G", "a", "b", "b", "a", "n", "a"].

We can use the Array.join() method to combine these characters back to a complete string.

function convertHTML(str) {
  // &colon;&rpar;

  let strArr = str.split('')

  strArr.map((char, i) => {
	if (char == "&") {
		strArr.splice(i, 1, "&amp;")
	} 
	if (char == "<"){
		strArr.splice(i, 1, "&lt;")
	}
	if (char == ">"){
		strArr.splice(i, 1, "&gt;")
	}
	if (char == "\""){
		strArr.splice(i, 1, "&quot;")
	}
	if (char == "'"){
		strArr.splice(i, 1, "&apos;")
	}
     
  })

  return strArr.join("");
}

convertHTML("Dolce & Gabbana");

Test this code in your browser console

Recap

That's all there is to it! We were able to step through the freeCodeCamp algorithm "Convert HTML Entities" using a few of the most helpful JavaScript methods. We used the String.split(), Array.map(), Array.splice(), and Array.join() methods.

Definitely send me any of your solutions, improvements, or real-world use cases you've come up with and I'd be happy to feature them!

Shoot me an email at [email protected] with any questions and if you enjoyed this, stay tuned and subscribe below! 👇

Help us improve our content