1. function sanitizeQueryString(queryString) {
  2. const params = {};
  3. if (!queryString) {
  4. return "Error: Query string is empty.";
  5. }
  6. const pairs = queryString.split('&');
  7. for (const pair of pairs) {
  8. const [key, value] = pair.split('=');
  9. if (!key) {
  10. return "Error: Invalid query parameter format.";
  11. }
  12. // Sanitize key - allow only alphanumeric characters and underscores
  13. const sanitizedKey = key.replace(/[^a-zA-Z0-9_]/g, '');
  14. if (!sanitizedKey) {
  15. return "Error: Invalid query parameter key.";
  16. }
  17. // Sanitize value - remove potentially harmful characters
  18. if (value) {
  19. const sanitizedValue = value.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
  20. params[sanitizedKey] = sanitizedValue;
  21. } else {
  22. params[sanitizedKey] = ""; //Handle empty values
  23. }
  24. }
  25. return params;
  26. }

Add your comment