Remove everything after a certain character in a string but keep wrapped in tag

I am iterating through multiple elements with nested text and need to remove everything after the ‘+’ character but keep wrapped in the tag.

Current Html:

<div class="v-event-timed" ><div class="pl"><strong>Test Demo</strong>, 1:38 AM + 11:38 AM</div></div>

Desired Html Output:

<div class="v-event-timed" ><div class="pl"><strong>Test Demo</strong>, 1:38 AM</div></div>

JS – (this keeps last characters, not correct):

this.$el.querySelectorAll('.v-calendar .v-event-timed').forEach((div: HTMLElement, i:number, arr:NodeListOf<HTMLElement>) => {
arr[i].textContent = arr[i].textContent.replace("+", "")
})

JS – (this removes all tags, not correct):

this.$el.querySelectorAll('.v-calendar .v-event-timed').forEach((div: HTMLElement, i:number, arr:NodeListOf<HTMLElement>) => {
    arr[i].textContent = arr[i].textContent.substr(0, arr[i].textContent.lastIndexOf("+"));
    })

Answer

Select the child nodes, alter the text of the text node.

var plChildren = document.querySelector(".pl").childNodes;
plChildren[1].textContent = plChildren[1].textContent.replace(/s+.*/, '');
<div class="v-event-timed" ><div class="pl"><strong>Test Demo</strong>, 1:38 AM + 11:38 AM</div></div>

so for multiple

document.querySelectorAll(".pl").forEach( function (elem) {
  var plChildren = elem.childNodes;
  plChildren[1].textContent = plChildren[1].textContent.replace(/s+.*/, '');
});
<div class="v-event-timed" ><div class="pl"><strong>Test Demo</strong>, 1:38 AM + 11:38 AM</div></div>
<div class="v-event-timed" ><div class="pl"><strong>Test Demo</strong>, 1:38 AM + 11:38 AM</div></div>
<div class="v-event-timed" ><div class="pl"><strong>Test Demo</strong>, 1:38 AM + 11:38 AM</div></div>

Leave a Reply

Your email address will not be published. Required fields are marked *