The text content to escape
The text with all XML special characters properly escaped
// Basic escaping
escapeXml('Hello & goodbye');
// Returns: 'Hello & goodbye'
// Escaping all special characters
escapeXml('Price < \$10 & > \$5');
// Returns: 'Price < \$10 & > \$5'
// Escaping quotes in text
escapeXml('She said "Hello" and I\'m happy');
// Returns: 'She said "Hello" and I'm happy'
// Preventing XML injection
escapeXml('</voice><voice name="malicious">Evil text');
// Returns: '</voice><voice name="malicious">Evil text'
// Safe for use in SSML
const userInput = 'Tom & Jerry <script>alert("XSS")</script>';
const safeText = escapeXml(userInput);
const ssml = `<speak><voice name="en-US-AvaNeural">${safeText}</voice></speak>`;
// Result: Valid SSML with escaped user input
Escapes special XML characters in text content to ensure valid XML output.
This function replaces the five XML special characters with their corresponding entity references to prevent XML parsing errors and potential security issues like XML injection attacks. The order of replacements is critical - ampersand must be replaced first to avoid double-escaping entity references.
The five XML entities that must be escaped are:
&
(ampersand) becomes&
<
(less than) becomes<
>
(greater than) becomes>
"
(double quote) becomes"
'
(single quote/apostrophe) becomes'
This function is essential when inserting user-provided or dynamic content into SSML documents to ensure the XML remains well-formed and secure.