Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Javascript: encode(decode) html text into html entity
// encode(decode) html text into html entity
var decodeHtmlEntity = function(str) {
return str.replace(/&#(\d+);/g, function(match, dec) {
return String.fromCharCode(dec);
});
};
var encodeHtmlEntity = function(str) {
var buf = [];
for (var i=str.length-1;i>=0;i--) {
buf.unshift(['&#', str[i].charCodeAt(), ';'].join(''));
}
return buf.join('');
};
var entity = '高级程序设计';
var str = '高级程序设计';
console.log(decodeHtmlEntity(entity) === str);
console.log(encodeHtmlEntity(str) === entity);
// output:
// true
// true
@eladkarako
Copy link

eladkarako commented Feb 12, 2016

with Unicode support (\uWXYZ):

function encodeHtmlEntity(str) {
  return str.replace(/[\u00A0-\u9999\<\>\&\'\"\\\/]/gim, function(c){
    return '&#' + c.charCodeAt(0) + ';' ;
  });
}

or as bookmarklet (placed in your bookmark-toolbar to use whenever..)

javascript:(function(){prompt("output:",prompt("∞ to HTML-Entity:","<div>❝Likė A Ƀoŝš❞ ©®</div>").replace(/[\u00A0-\u9999\<\>\&\'\"\\\/]/gim,function(c){return '&#'+c.charCodeAt(0)+';'}));return true;}());



sorry about the watermark, I've took it from here

@cdaiga
Copy link

cdaiga commented Jun 20, 2016

Thanks so much. I just used it.

@Hardhik
Copy link

Hardhik commented Sep 16, 2016

Thanks a lot for this!
What if my string also has hexadecimal along with decimal values?

@xorgy
Copy link

xorgy commented Jan 12, 2017

function encodeHtmlEntity(str) {
  var buf = '';
  for (var i=0; i < str.length; i++) {
    buf += '&#'+ str.charCodeAt(i) + ';';
  }
  return buf;
};

Come on man.

@wrathyz
Copy link

wrathyz commented Jan 25, 2018

Thank you

@gkilmain
Copy link

gkilmain commented Feb 8, 2018

Thank you for nice one

@lfg6000
Copy link

lfg6000 commented Jul 11, 2019

Thank You. It was good of you to post it.

@Tolluset
Copy link

Tolluset commented Jun 3, 2020

Thanks!

@kachar
Copy link

kachar commented Jan 6, 2021

TypeScript version:

const decodeHtmlEntity = function (str: string) {
  return str.replace(/&#(\d+);/g, function (match: string, dec: number) {
    return String.fromCharCode(dec)
  })
}

const encodeHtmlEntity = function (str: string) {
  const buf = []
  for (let i = str.length - 1; i >= 0; i--) {
    buf.unshift(['&#', str.charCodeAt(i), ';'].join(''))
  }
  return buf.join('')
}

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