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
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>
You can use querSelectorAll
and replace
.{3}$
.{3}
- Match anything except new line 3 times$
- End of stringvar 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With