Reputation: 17
I have a simple HTML form with an input of name="comment"
. I am displaying the result with jsx in a react app using {formData.comment}
.
The form and result works fine for normal input like hello world
but for special character input like
that's
output is that's
.
How to get the value as it is sent to the form?
Upvotes: 0
Views: 219
Reputation: 16
How did you get your data ?
function Form() {
const [comm,setComm] = React.useState()
const submitHandler = e => {
e.preventDefault()
const data = new FormData(e.target)
setComm(data.get('comment'))
};
return (
<form onSubmit={submitHandler}>
<input
name="comment"
type="text"
/>
<button type="submit">
submit
</button>
<div>Result : {comm}</div>
</form>
);
}
Upvotes: 0
Reputation: 9063
You'd have to replace the character entities. I don't think there's a native way of doing this in Javascript (if so someone please comment it or add an answer with it). But luckily doing it manually is quite simple:
// The list of characters to escape
const htmlEscapes = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/'
};
// Sample string with an apostrophe character entity in it
let str = 'that's';
// Loop over the entities to escape and regex them out
Object
.entries(htmlEscapes)
.forEach(([plain, hexCode]) => str = str.replace(new RegExp(hexCode, 'g'), plain));
// String is now sanitized
console.log(str);
This is just one sample way of doing it, point being you'd have to process the string to replace them
Upvotes: 1