Jishnu V S Jishnu V S - 1 month ago 9
CSS Question

How to find the all numbers inside the div and add <span></span> tag using jquery?

I have a

DOM
like this

<div class="main_div">
<p>A car averages 27 miles per gallon. If gas costs $4.04 per gallon, which of the following is closest to how much the gas would cost for this car to travel 2,727 typical miles?</p>
</div>


i just want to add span tag to all numbers like

<div class="main_div">
<p>A car averages <span> 27 </span> miles per gallon. If gas costs $<span>4.04</span> per gallon, which of the following is closest to how much the gas would cost for this car to travel <span>2,727</span> typical miles?</p>
</div>


I have tried so may ways and check this links too

Javascript/jquery get number value inside of element

How to get number inside a div with jquery

Jquery - Adding all numbers inside span of a particular class

but this can only select first numbers only i want to select all number inside the div , if the div contains 20 numbers i just need to add span all numbers , is this possible ? best answers must be appreciated ..

Answer

Use regex to match number and wrap in in <span>

$(document).ready(function() {
  $('.main_div p').each(function() {
    $(this).html(
      $(this).text().replace(/([0-9]+[.,][0-9]+|[0-9]+)/g, '<span>$1</span>')
    );
  })
});
span {
  text-decoration: underline;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main_div">
  <p>A car averages 27 miles per gallon. If gas costs $4.04 per gallon, which of the following is closest to how much the gas would cost for this car to travel 2,727 typical miles? I am years old 24, because of 24.</p>
  <p>A car averages 27 miles per gallon. If gas costs $4.04 per gallon, which of the following is closest to how much the gas would cost for this car to travel 2,727 typical miles?</p>
</div>

Comments