How to Safely Enter Single/Double Quotes in HTML inputs from JavaScript
Imagine a scenario where you’re dealing with an HTML form with text boxes where you are passing the data to the back end by using JavaScript methods. If a user enters a single quote or a double quote in the textbox, the JavaScript could go bonkers having not being properly validated.
There is a simple fix for that: Replace the quotes with Character codes.
The double quote (“) has a Character code \x27
and for the single quote (‘) \x22
. So to fix this, you add this code.
var txt = f.txt.value.replace(/\'/,'\x27').replace(/\"/,'\x22');
This replaces the characters with char codes in the textbox called txt
in the form named f
and assigns to the var txt
. (I used JQuery to get values of the txt
.. That’s JQuery notation. But you can also use vanilla JS for this)
You can find another use/example here