Skip to content

Instantly share code, notes, and snippets.

@jenstornell
Last active October 9, 2019 13:08
Show Gist options
  • Save jenstornell/235323f08b872d52eb3e41b7a2b43ca7 to your computer and use it in GitHub Desktop.
Save jenstornell/235323f08b872d52eb3e41b7a2b43ca7 to your computer and use it in GitHub Desktop.
class Inside {
set(selector, strStart, strEnd) {
this.selector = selector;
this.strStart = strStart;
this.strEnd = strEnd;
this.position = null;
this.counter = null;
this.parts = null;
this.setHtml();
this.setPosition();
this.setCounter();
this.setChunks();
}
setHtml() {
this.html = document.querySelector(this.selector).innerHTML;
}
setPosition() {
const start = this.html.indexOf(this.strStart);
const end = this.html.indexOf(this.strEnd, start);
if (start == -1 || end == -1) return;
this.position = {
start: start,
end: this.html.indexOf(this.strEnd, start),
finish: this.html.length
};
}
setCounter() {
if (!this.position) return;
this.counter = {
before: this.position.start,
match: this.position.end - this.position.start + this.strEnd.length,
after: this.position.finish - this.position.end
};
}
setChunks() {
if (!this.position) return;
this.parts = {
before: this.html.substr(0, this.count.before),
match: this.html.substr(this.position.start, this.count.match),
after: this.html.substr(this.position.end + this.strEnd.length, this.count.after)
};
}
get pos() {
return this.position;
}
get count() {
return this.counter;
}
get chunks() {
return this.parts;
}
}
@jenstornell
Copy link
Author

jenstornell commented Oct 9, 2019

<main>
        <p>Some text</p>

        BEFORE
        
        AFTER

        <p>Some more text</p>
  <!-- KEYWORDS: one --></main>

<script>
  document.addEventListener("DOMContentLoaded", () => {
    const InsideObj = new Inside();
    InsideObj.set('main', '<!-- KEYWORDS:', '-->');
    console.log(InsideObj.chunks);
  });
</script>

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