Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last 3 characters of every list element and change it to # with Javascript [closed]

I have a set of list of phone number on HTML. I need to replace every last 3 digits with ###.

What is the best approach to do this with pure Javascript?

<ul>
  <li>
      <dl>
        <dt>Phone:</dt>
        <dd class="phone">333444555</dd>
      </dl>
  </li>
  <li>
      <dl>
        <dt>Phone:</dt>
        <dd class="phone">777888999</dd>
      </dl>
  </li>
</ul>

The expected result should be something like this

<ul>
  <li>
      <dl>
        <dt>Phone:</dt>
        <dd class="phone">333444###</dd>
      </dl>
  </li>
  <li>
      <dl>
        <dt>Phone:</dt>
        <dd class="phone">777888###</dd>
      </dl>
  </li>
</ul>

Appreciate all answers..

Cheers

like image 298
KRMZ Avatar asked Dec 17 '22 16:12

KRMZ


2 Answers

You can use querySelectorAll() to get all the elements with a class of "phone", then loop through them returning a new string without the last 3 characters by using String.prototype.slice(), finally concatenate the ###:

var phones = document.querySelectorAll('.phone');
phones.forEach(function(p){
  var t = p.textContent;
  p.textContent = t.slice(0, -3) + '###';
});
<ul>
  <li>
      <dl>
        <dt>Phone:</dt>
        <dd class="phone">333444555</dd>
      </dl>
  </li>
  <li>
      <dl>
        <dt>Phone:</dt>
        <dd class="phone">777888999</dd>
      </dl>
  </li>
</ul>
like image 110
Mamun Avatar answered Jan 05 '23 18:01

Mamun


You can use querSelectorAll and replace

.{3}$
  • .{3} - Match anything except new line 3 times
  • $ - End of string

var phones = document.querySelectorAll('.phone');
phones.forEach(function(p){
  var t = p.textContent;
  p.textContent = t.replace(/.{3}$/, '###');
});
<ul>
  <li>
      <dl>
        <dt>Phone:</dt>
        <dd class="phone">333444555</dd>
      </dl>
  </li>
  <li>
      <dl>
        <dt>Phone:</dt>
        <dd class="phone">777888999</dd>
      </dl>
  </li>
</ul>
like image 24
Code Maniac Avatar answered Jan 05 '23 18:01

Code Maniac