Skip to content

Instantly share code, notes, and snippets.

@cyco130
Last active May 24, 2023 10:01
Show Gist options
  • Save cyco130/72cec1527822d28d0aec89510d74d45c to your computer and use it in GitHub Desktop.
Save cyco130/72cec1527822d28d0aec89510d74d45c to your computer and use it in GitHub Desktop.
Copilot Chat - First Try

cyco130

Are there any problems with this code?

export function escapeHtml(text: string): string {
	return text
		.replace(/</g, "&lt;")
		.replace(/&/g, "&amp;")
		.replace(/>/g, "&gt;")
		.replace(/"/g, "&quot;")
		.replace(/'/g, "&#x27;");
}

GitHub Copilot

The code you provided looks fine to me. It exports a function called escapeHtml that takes a string as input and returns a new string with certain characters replaced by their corresponding HTML entities. Is there anything specific you're concerned about?

cyco130

How would it escape the string "<"?

GitHub Copilot

The escapeHtml function would escape the string "<" by replacing it with the HTML entity &lt;. So the resulting escaped string would be "&lt;".

cyco130

But it will not stop there, it will then proceed to escape the ampersand character, won't it?

GitHub Copilot

Yes, you're correct. The escapeHtml function will also escape the ampersand character by replacing it with the HTML entity &amp;. So the resulting escaped string would be "&lt;&amp;".

cyco130

Now do you see the problem?

GitHub Copilot

I apologize for my earlier response. You're correct that there is a problem with the escapeHtml function. The order of the replacements is incorrect, which can lead to incorrect escaping of certain characters. Specifically, if the input string contains an ampersand character followed by a less-than character, the function will escape the less-than character first, resulting in an invalid HTML entity.

To fix this issue, the function should replace the ampersand character first, before replacing the less-than character. Here's the corrected implementation:

export function escapeHtml(text: string): string {
    return text
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#x27;");
}

I hope this helps!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment