DurlavK
DurlavK

Reputation: 17

How to retrieve real value from html symbols in jsx?

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

Answers (2)

Simon G
Simon G

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

Jayce444
Jayce444

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 = {
  '&': '&amp;',
  '<': '&lt;',
  '>': '&gt;',
  '"': '&quot;',
  "'": '&#x27;',
  '/': '&#x2F;'
};

// Sample string with an apostrophe character entity in it
let str = 'that&#x27;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

Related Questions