Skip to content

Instantly share code, notes, and snippets.

@archisgore
Created August 18, 2019 19:48
Show Gist options
  • Save archisgore/945cc8e29817d205f3786bd7d859fa7c to your computer and use it in GitHub Desktop.
Save archisgore/945cc8e29817d205f3786bd7d859fa7c to your computer and use it in GitHub Desktop.
Apply HTML tags across spans of text using Javascript.
function applyTagAt(text, start, end, startTag, endTag) {
var text2 = "";
var counter = 0;
var intag = false;
var inescape = false;
var tagstarted = false;
for (var i = 0; i < text.length; i++) {
if (text.charAt(i) == '<') {
intag = true;
if (tagstarted) {
text2 += endTag; //End our tag
if (counter == end) {
tagstarted = false;
}
}
}
if (counter == start && intag == false && inescape == false) {
text2 += startTag;
tagstarted = true;
text2 += text.charAt(i);
} else if (counter == end && inescape == false && tagstarted == true) {
text2 += endTag;
tagstarted = false;
text2 += text.charAt(i);
} else {
text2 += text.charAt(i);
}
if (intag == true && text.charAt(i) == '>') {
intag = false;
if (tagstarted) {
text2 += startTag;
}
} else if (intag == false && text.charAt(i) == '&') {
inescape=true;
} else if (inescape == true && text.charAt(i) == ';') {
inescape=false;
counter++;
} else if (intag == false && inescape == false) {
counter++;
}
}
// counter can be incremented at the end
if (counter == end && intag == false && inescape == false && tagstarted == true) {
text2 += endTag;
}
//replace all instances of <startTag,endTag> (<em></em>) with empty string
var text3 = text2.replace(startTag+endTag, "");
while (text3 != text2) {
text2 = text3;
text3 = text2.replace(startTag+endTag, "");
}
return text2;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment