Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How can I use tagged templates to sanitize user input in JavaScript without manually escaping characters?
Asked on Dec 26, 2025
Answer
Tagged templates in JavaScript can be used to sanitize user input by processing template literals with a function that escapes potentially harmful characters. This approach helps prevent injection attacks by ensuring that user input is safely handled.
<!-- BEGIN COPY / PASTE -->
function sanitize(strings, ...values) {
return strings.reduce((result, string, i) => {
const value = values[i - 1];
const safeValue = String(value)
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
return result + safeValue + string;
});
}
const userInput = "<script>alert('XSS')</script>";
const safeHTML = sanitize`User input: ${userInput}`;
console.log(safeHTML); // Output: User input: <script>alert('XSS')</script>
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The "sanitize" function is a tagged template function that processes the template literal.
- It iterates over the "strings" and "values" arrays to construct a safe string.
- Special characters in user input are replaced with their HTML entity equivalents to prevent code injection.
- This example demonstrates how to handle a potentially harmful script tag in user input.
- Always validate and sanitize user input, especially if it's rendered in a web page.
Recommended Links:
