Skip to content

Instantly share code, notes, and snippets.

@luislobo14rap
Last active January 4, 2018 19:19
Show Gist options
  • Save luislobo14rap/d6ec6e8b34a740e3cd66f3ac08ff2e4d to your computer and use it in GitHub Desktop.
Save luislobo14rap/d6ec6e8b34a740e3cd66f3ac08ff2e4d to your computer and use it in GitHub Desktop.
String.prototype.htmlEntities = function( reverse = 0 ){
let thisString = this;
let entities = [' ', '<', '>', '"', '\'', '¢', '£', '¥', '€', '©', '®'];
let htmlEntities = ['&nbsp;', '&lt;', '&gt;', '&quot;', '&apos;', '&cent;', '&pound;', '&yen;', '&euro;', '&copy;', '&reg;'];
if( reverse == 0 ){
thisString = thisString.replace(/&/g, 'ΠπϖⲠⲡhE');
for(let i = 0; i < 11; i++){
thisString = thisString.replace( new RegExp( entities[i] , 'g'), htmlEntities[i] ).replace(/ΠπϖⲠⲡhE/g, '&amp;');
};
}else{
entities.push('&');
htmlEntities.push('&amp;');
for(let i = 0; i < 12; i++){
thisString = thisString.replace( new RegExp( htmlEntities[i] , 'g'), entities[i] );
};
};
return thisString;
};
/*
EXAMPLE:
> '<span>hi</span>'.htmlEntities()
< '&lt;span&gt;hi&lt;/span&gt;'
> '&lt;span&gt;hi&lt;/span&gt;'.htmlEntities(1) //USE 1 FOR REVERSE
< '<span>hi</span>'
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment