Home > Back-end >  remove part of text in a div using javacript
remove part of text in a div using javacript

Time:12-04

i would like to remove part (4 first characters) of a text in a list of span tags (filtered by the class name):

<span class="time">00:00:50</span>
<span class="time">00:01:22</span>
<span class="time">00:02:44</span>

i would like to get this:

<span class="time">0:50</span>
<span class="time">1:22</span>
<span class="time">2:44</span>

i try some codes using text.substr(1, 4) but none of them works, could someone help me?

CodePudding user response:

You can use a regular expression to match it

document.querySelectorAll(".time").forEach(function (elem) {
  elem.textContent = elem.textContent.match(/[1-9]?\d:\d\d$/)[0];
});
<span class="time">00:00:50</span>
<span class="time">00:01:22</span>
<span class="time">00:02:44</span>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

substr if it will always be X:XX

document.querySelectorAll(".time").forEach(function (elem) {
  elem.textContent = elem.textContent.substr(-5);
});
<span class="time">00:00:50</span>
<span class="time">00:01:22</span>
<span class="time">00:02:44</span>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

How do I chop/slice/trim off last character in string using Javascript?

Look into this post first, there you can get an idea, use the code presented there in any browser development console and you will see in real time the results from those manipulations.

It's not that hard to do some actual research, keep it up you can learn so much if you try.

For example try this:

let str = "00:00:50";
str = str.substring(3);
  • Related