0 day streak
javascript / beginner
Snippet

Escaping Special Characters in Raw Input for Security in Vue

Cross-Site Scripting (XSS) occurs when malicious code is injected into a web application. Converting special characters into safe HTML entities ensures that untrusted input is treated as plain text rather than executable markup.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { ref } from 'vue';
export default {
setup() {
const safeMessage = ref('');
function sanitizeText(untrustedString) {
const map = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;' };
return untrustedString.replace(/[&<>"']/g, char => map[char]);
}
function handleUserInput(input) {
safeMessage.value = sanitizeText(input);
}
return { safeMessage, handleUserInput };
}
};
vue
Breakdown
1
const map = { '&': '&amp;', '<': '&lt;', ... };
Creates a dictionary mapping dangerous HTML characters to their safe entity equivalents.
2
return untrustedString.replace(/[&<>"']/g, char => map[char]);
Substitutes all matching special characters across the string with the safe entities.