CONVERT SPECIAL CHARACTERS TO HTML IN JAVASCRIPT

Ankita Pandey

Total Post:183

Points:1285
Posted by  Ankita Pandey
HTML5 
 1628  View(s)
Ratings:
Rate this:

Does any one know how to convert special characters to HTML in Javascript?

Example:

'&' (ampersand) becomes '&amp' 
'"' (double quote) becomes '&quot' when ENT_NOQUOTES is not set.
''' (single quote) becomes '&#039' only when ENT_QUOTES is set.
'<' (less than) becomes '&lt'
'>' (greater than) becomes '&gt'

Thanks in advance.

  1. Sumit Kesarwani

    Post:378

    Points:2694
    Re: Convert special characters to HTML in Javascript

    Hi Ankita,


    You need a function that does something like

    return mystring.replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/"/g, "&quot;");

    But taking into account your desire for different handling of single/double quotes.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!