Skip to content

Instantly share code, notes, and snippets.

@daraul
Last active February 11, 2024 01:18
Show Gist options
  • Save daraul/7057c25495dc0284d1c4e77997d25938 to your computer and use it in GitHub Desktop.
Save daraul/7057c25495dc0284d1c4e77997d25938 to your computer and use it in GitHub Desktop.
Decode PHP's htmlspecialchars encoding with Javascript
return function(text) {
var map = {
'&': '&',
'&': "&",
'&lt;': '<',
'&gt;': '>',
'&quot;': '"',
'&#039;': "'",
'&#8217;': "’",
'&#8216;': "‘",
'&#8211;': "–",
'&#8212;': "—",
'&#8230;': "…",
'&#8221;': '”'
};
return text.replace(/\&[\w\d\#]{2,5}\;/g, function(m) { return map[m]; });
};
@daraul
Copy link
Author

daraul commented Apr 29, 2016

Thanks to Kip for his code that helped me with this: http://stackoverflow.com/a/4835406/3403924

@zzell
Copy link

zzell commented Dec 27, 2017

Thanks man, this helped a lot.

@GermanPearls
Copy link

Thank you.

@albirlak
Copy link

Thanks!

@ThibaultPetit
Copy link

Thank you !

@janbarasek
Copy link

Rewrited to typesccript:

const htmlSpecialCharsDecode = (text: string): string => {
  const map: Record<string, string> = {
    '&amp;': '&',
    '&#038;': '&',
    '&nbsp;': ' ',
    '&lt;': '<',
    '&gt;': '>',
    '&quot;': '"',
    '&#039;': "'",
    '&#8217;': '’',
    '&#8216;': '‘',
    '&#8211;': '–',
    '&#8212;': '—',
    '&#8230;': '…',
    '&#8221;': '”',
  };

  return text.replace(/\&[\w\d\#]{2,5}\;/g, (m) => map[m] ?? m);
};

export default htmlSpecialCharsDecode;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment