javascript / beginner
Snippet
Preventing Script Injection in Search Query State
Input sanitization is a fundamental defensive security practice. By stripping potentially dangerous HTML tag characters like '<' and '>' from user-supplied strings before persisting or reflecting them, you reduce the risk of cross-site scripting (XSS) and malformed state manipulation.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
<script setup>import { ref } from 'vue';const rawSearchInput = ref('');const sanitizedSearch = ref('');function applySafeSearch(input) {const cleanString = String(input).replace(/[<>]/g, '').trim();sanitizedSearch.value = cleanString;}</script>
vue
Breakdown
1
const cleanString = String(input).replace(/[<>]/g, '').trim();
Converts input to a string, removes angle brackets with a regular expression, and trims whitespace.
2
sanitizedSearch.value = cleanString;
Stores the sanitized text into the state for safe downstream use.