javascript / intermediate
Snippet
Sanitizing Untrusted HTML Input Before v-html Rendering
Escaping dangerous HTML entity characters before binding user-supplied strings ensures protection against Cross-Site Scripting (XSS) vulnerabilities in Vue templates.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { ref, computed } from 'vue';function sanitizeHtml(dirtyString) {const htmlEntities = {'&': '&','<': '<','>': '>','"': '"',"'": '''};return String(dirtyString).replace(/[&<>"']/g, (char) => htmlEntities[char]);}export function useSafeUserInput(rawInput = '') {const userContent = ref(rawInput);const safeContent = computed(() => sanitizeHtml(userContent.value));return { userContent, safeContent };}
vue
Breakdown
1
const htmlEntities = { ... };
Maps sensitive HTML control characters to their safe entity counterparts.
2
return String(dirtyString).replace(/[&<>"']/g, (char) => htmlEntities[char]);
Executes a global regular expression replacement targeting all vulnerable characters.
3
const safeContent = computed(() => sanitizeHtml(userContent.value));
Computes a sanitized string reactively whenever the underlying input value changes.