Skip to content

Instantly share code, notes, and snippets.

@rfprod
Last active April 22, 2017 15:59
Show Gist options
  • Save rfprod/07b8982be523e39a0dd6 to your computer and use it in GitHub Desktop.
Save rfprod/07b8982be523e39a0dd6 to your computer and use it in GitHub Desktop.
Convert HTML Entities
function convertHTMLent(str) {
// :)
var replace = ["&","<",">"];
replace.push("'");
replace.push('"');
var replacements = ["&amp;","&lt;","&gt;","&apos;","&quot;"];
var counter = 0;
// count entries to replace
for (var i=0;i<replace.length;i++){
for (var j=0;j<str.length;j++){
if (replace[i] == str[j]){
counter = counter + 1;
}
}
}
for (var k=0;k<counter;k++){
if (str.indexOf("& ") > -1){
str = str.replace(/&/,replacements[0]);
}
if (str.indexOf("<") > -1){
str = str.replace(/</,replacements[1]);
}
if (str.indexOf(">") > -1){
str = str.replace(/>/,replacements[2]);
}
if (str.indexOf("'") > -1){
str = str.replace(/'/,replacements[3]);
}
if (str.indexOf('"') > -1){
str = str.replace(/"/,replacements[4]);
}
}
return str;
}
convertHTMLent('Stuff in "quotation marks"');

Convert HTML Entities

Converts the characters "&", "<", ">", '"' (double quote), and "'" (apostrophe), in a string to their corresponding HTML entities.

A script by V.

License.

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