Here is a general encode procedure:

var lt = /</g, 
    gt = />/g, 
    ap = /'/g, 
    ic = /"/g;
value = value.toString().replace(lt, "&lt;").replace(gt, "&gt;").replace(ap, "&#39;").replace(ic, "&#34;");

If your user doesn't submit anything to your server you don't even need the above. If the user submits and you are using the user input then the above should be safe. As long as the '<' and '>' are globally sanitized and the parenthesis also are you are good to go.

Answer from Konstantin Dinev on Stack Overflow
🌐
Mozilla
developer.mozilla.org › en-US › docs › Web › Security › Attacks › XSS
Cross-site scripting (XSS) - Security | MDN
In both cases, the general approach ... external input in your site's pages, there are two main defenses against XSS: Use output encoding and sanitization to prevent input from becoming executable....
Discussions

[AskJS] How do you protect against XSS?
Generally headers within the HTML document which prevent scripts loading from any other domain other than itself. Ideally, you'd want these headers to exist on the server, say like an Apache or NGINX config file, but you can place them in the HTML document itself via the meta tag. The Content Security Policy is by far the latest and most strict of all security headers, as it's a catch-all against any outside domain assets including content from CDN's and Google Analytics. Furthermore, inline scripts will be blocked as well. You'll need to manage the exceptions one by one. I'd recommend a security header generator of some sort to make sure you're not blocking your own assets. Example meta tag: ``` ``` More on reddit.com
🌐 r/javascript
22
21
July 29, 2019
How exactly does Cross Site Scripting (XSS) work?
There are 3 basic types of XSS: reflected, stored and DOM based. Stored XSS is an attack on a site that allows user to submit and store HTML in some way (eg in a comment or user profile). If the input is not properly filtered, an attacker can embed malicious JavaScript in the HTML. Then anyone who visits the site and happens to bring up that user's comment will get the payload. Reflected XSS is when a site takes user input and embeds it in the page, but without storing it on the server. An example would be a multistep form that uses your answer to the first question to determine the next question, eg "what's your favourite food?" If the user answers "pizza", the form then asks "what's your favourite pizza?" But the user answers with , the form will ask "what's your favourite " if it doesn't correctly filter/validate the user input. It's "reflected" because the user's input is reflected back to them in the HTTP response from the server. But since this isn't stored on the server, the attacker would need to trick the user into opening a crafted URL with the malicious answer embedded in it. DOM XSS is similar, but the difference is that the HTTP response from the server doesn't change, it's only what happens on the client side that differs. This is where the site takes user input and uses it directly in JavaScript on the page. The user input never hits the server, so the server-side code can't filter/validate the input, instead the JavaScript itself must do it. Again, you would need to trick a user into opening a specially crafted URL to execute this attack. Aside from safely encoding/filtering/validating user input in code, the other way to prevent these attacks is by implementing a strict Content Security Policy on the web server that only allows scripts with the right nonce or hash to be executed. More on reddit.com
🌐 r/cybersecurity
13
86
August 21, 2024
Is this good enough to prevent XSS attacks?
Why try to reinvent the wheel when you can use packages like https://www.npmjs.com/package/sanitize-html More on reddit.com
🌐 r/webdev
4
3
July 23, 2021
XSS in modern web development
Most browsers support HTTP headers that can add more restrictions to prevent XSS... look into Content-Security-Policy, Referrer-Policy, Strict-Transport-Security, X-Content-Type-Options, X-Frame-Options, X-XSS-Protection More on reddit.com
🌐 r/webdev
27
84
January 22, 2018
People also ask

How can developers prevent XSS attacks?
Developers may avoid XSS attacks by checking user input, encoding output data, and allowing only malicious scripts. Periodic security audits and content security policies also reduce risks.
🌐
sentinelone.com
sentinelone.com › cybersecurity-101 › threat-intelligence › how-to-prevent-cross-site-scripting-xss-attacks
How to Prevent Cross-Site Scripting (XSS) Attacks?
What are XSS Attacks?
XSS attacks involve injecting malicious scripts into websites to allow hackers to access sensitive user data. XSS attacks exploit web application vulnerabilities and often use user input or manipulated URLs.
🌐
sentinelone.com
sentinelone.com › cybersecurity-101 › threat-intelligence › how-to-prevent-cross-site-scripting-xss-attacks
How to Prevent Cross-Site Scripting (XSS) Attacks?
What are the Tools and Solutions to Detect and Prevent XSS Attacks?
Solutions and tools include vulnerability scanners, web application firewalls, and advanced threat detection systems. These help detect vulnerabilities and block malicious scripts from running.
🌐
sentinelone.com
sentinelone.com › cybersecurity-101 › threat-intelligence › how-to-prevent-cross-site-scripting-xss-attacks
How to Prevent Cross-Site Scripting (XSS) Attacks?
🌐
OWASP Cheat Sheet Series
cheatsheetseries.owasp.org › cheatsheets › Cross_Site_Scripting_Prevention_Cheat_Sheet.html
Cross Site Scripting Prevention - OWASP Cheat Sheet Series
Please look at the OWASP Java Encoder JavaScript encoding examples for examples of proper JavaScript use that requires minimal encoding. For JSON, verify that the Content-Type header is application/json and not text/html to prevent XSS. “CSS Contexts” refer to variables placed into inline CSS, which is common when developers want their users to customize the look and feel of their webpages. Since CSS is surprisingly powerful, it has been used for many types of attacks.
🌐
PortSwigger
portswigger.net › web-security › cross-site-scripting
What is cross-site scripting (XSS) and how to prevent it? | Web Security Academy
Cross-site scripting works by ... malicious JavaScript to users. When the malicious code executes inside a victim's browser, the attacker can fully compromise their interaction with the application. If you're already familiar with the basic concepts behind XSS vulnerabilities ...
🌐
Reddit
reddit.com › r/javascript › [askjs] how do you protect against xss?
r/javascript on Reddit: [AskJS] How do you protect against XSS?
July 29, 2019 -

Greetings, I am working on web app where i have back end utilizing spring And front end utilizing JavaScript And jQuery. I need to implement total xss protection on the front end side. How do you handle xss to make your app Safe? Would you recommend any libraries which can be used to filter input And other things related to xss (these libraries should be safe) Or how do you usually defend against xss when you Are developing such application ? Thank you

🌐
SentinelOne
sentinelone.com › cybersecurity-101 › threat-intelligence › how-to-prevent-cross-site-scripting-xss-attacks
How to Prevent Cross-Site Scripting (XSS) Attacks?
January 8, 2026 - You can also encode attribute values. Another good practice to prevent XSS attacks is filtering the data received on the client side. Filtering data removes dangerous characters such as tags, HTML event handlers, malicious JavaScript elements, etc.
Find elsewhere
🌐
PreEmptive
preemptive.com › blog › how-to-prevent-xss-attacks
How to Prevent XSS Attacks | PreEmptive
January 8, 2026 - XSS attacks can happen to web applications with all types of coding languages or combinations thereof. Some of the languages that need XSS protection the most include: JavaScript: XSS attacks most often involve running malicious JavaScript code, making it one of the languages that is most ...
🌐
Telerik
telerik.com › blogs › how-to-prevent-cross-site-scripting-xss-javascript
How to Prevent Cross-Site Scripting (XSS) in JavaScript
October 13, 2023 - There are three types of XSS attacks: Reflected XSS, Stored XSS and DOM-based XSS. To prevent XSS attacks, it is crucial to sanitize all user input before it is displayed on a webpage using techniques like input validation and output encoding.
🌐
Medium
shashankvivek-7.medium.com › understanding-xss-and-preventing-it-using-pure-javascript-ef0668b37687
Understanding XSS and preventing it using Pure JavaScript | by Shashank Vivek | Medium
April 20, 2019 - To prevent this attack in pure JS, let’s write a custom function that looks out for special characters such as “<” , “>” and “&” , which can cause XSS attacks.
🌐
Medium
medium.com › @rameshvr › securing-your-code-strategies-for-preventing-xss-attacks-in-javascript-6c9e83e73451
Securing Your Code: Strategies for Preventing XSS Attacks in JavaScript | by Ramesh Rajagopal | Medium
December 19, 2023 - Use automated scanners and manual testing techniques to identify and fix any XSS issues before deployment. By implementing these strategies, you can significantly reduce the risk of XSS attacks in your JavaScript applications.
🌐
StackHawk
stackhawk.com › stackhawk, inc. › vulnerabilities and remediation › preventing xss attacks in typescript projects
Preventing XSS Attacks in TypeScript Projects
December 2, 2024 - If you look at all our functions and DOM manipulations, we’re using full-on TypeScript instead of plain old JavaScript! However, the way we’re manipulating the DOM is still incorrect. It still exposes a DOM XSS vulnerability. That means just using TypeScript won’t help. In the above codebase, let’s say that an attacker manages to inject a script and programmatically executes this:
🌐
Medium
article.arunangshudas.com › 6-strategies-to-mitigate-xss-attacks-in-node-js-2e788aeb003f
6 Strategies to Mitigate XSS Attacks in Node.js | by Arunangshu Das | Medium
March 24, 2025 - XSS attackers often try to steal session cookies to hijack user accounts. To prevent this, use HTTP-Only and Secure cookies, which cannot be accessed via JavaScript.
🌐
Vercel
vercel.com › kb › guide › understanding-xss-attacks
Understanding XSS Attacks | Vercel Knowledge Base
To reduce security gaps, always ensure validation rules and techniques are consistent on both client and server. Ensure any third-party React components or Next.js plugins you include do not introduce XSS vulnerabilities. XSS attacks can cause significant damage, but they can be completely avoided with the appropriate preventive measures.
🌐
Web Dev Simplified
blog.webdevsimplified.com › 2020-09 › javascript-xss
How To Prevent The Most Common Cross Site Scripting Attack
September 7, 2020 - If you write an img tag with no src it will run the onerror event which we can set to our own malicious JavaScript.
🌐
DEV Community
dev.to › saint_vandora › cross-site-scripting-xss-attacks-in-nodejs-understanding-preventing-and-mitigating-risks-4b2p
Cross-Site Scripting (XSS) Attacks in Node.js: Understanding, Preventing, and Mitigating Risks - DEV Community
October 6, 2023 - Client-Side JavaScript: If your ... JavaScript files and incorporates user input without proper validation, attackers can exploit this to execute malicious scripts. Protecting your Node.js application against XSS attacks requires a combination of best practices and security measures. Here are some essential steps to help you prevent XSS ...
🌐
DopeThemes
dopethemes.com › home › understanding and preventing xss attacks in javascript applications
Understanding and Preventing XSS Attacks in JavaScript Applications - DopeThemes
October 17, 2024 - Below are some best practices to follow for preventing XSS vulnerabilities in your JavaScript applications: Use frameworks with built-in XSS protection: JavaScript frameworks like Angular, React, and Vue come with built-in sanitization techniques ...
🌐
SugarCRM
support.sugarcrm.com › documentation › sugar_developer › sugar_developer_guide_13.3 › security › xss_prevention
XSS Prevention - Sugar Support
January 12, 2024 - These rules serve to protect the elements of your customizations that are most susceptible to XSS vulnerabilities: Create safe variables when injecting HTML via Handlebars templates or JavaScript methods such as: $(selector).html(variable), $(selector).before(variable), or $(selector).afte...
🌐
Splunk
splunk.com › en_us › blog › learn › cross-site-scripting-xss-attacks.html
Cross-Site Scripting (XSS) & How to Prevent Attacks | Splunk
Set the HttpOnly flag. You can set this flag in the cookies to prevent JavaScript code from accessing the cookies. Use the X-XSS-Protection header. Set this in browsers like Google Chrome and Microsoft Edge to prevent reflected XSS attacks.
🌐
TechTarget
techtarget.com › searchsecurity › answer › Whats-the-best-way-to-prevent-XSS-attacks
What's the best way to prevent XSS attacks? | TechTarget
This kind of attack is carried out with JavaScript in the victim's browser · To prevent XSS attacks, developers must validate user input by properly filtering out or escaping special characters and then encoding the output to prevent stored ...
🌐
MakeUseOf
makeuseof.com › home › programming › how to prevent cross-site scripting in node.js
How to Prevent Cross-Site Scripting in Node.js
June 18, 2022 - Therefore, the first preventative measure you must take is sanitizing all the input your application receives from its users. This is crucial because it detects the bogus data before the server executes it.