0 day streak
javascript / beginner
Snippet

Escaping Special Characters to Prevent Injection in Vue

Manually escaping HTML entities with a JavaScript regex replace ensures dangerous characters are converted into safe HTML entities. This defensive pattern neutralizes potential script injection before displaying or processing text.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<script setup>
import { ref } from 'vue';
const safeOutput = ref('');
function sanitizeInput(userInput) {
const entityMap = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#039;'
};
safeOutput.value = userInput.replace(/[&<>"']/g, char => entityMap[char]);
}
</script>
vue
Breakdown
1
const entityMap = { ... };
Defines a mapping dictionary from sensitive HTML characters to their safe entity codes.
2
safeOutput.value = userInput.replace(/[&<>"']/g, char => entityMap[char]);
Applies a global regex pattern and replaces every matched unsafe character with its escaped equivalent.