0

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 ..

Community
  • 1
  • 1
Jishnu V S
  • 8,164
  • 7
  • 27
  • 57

2 Answers2

5

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>
Justinas
  • 41,402
  • 5
  • 66
  • 96
3

Use regex on the divs html (or text if you are afraid to mess with the html).

replace the regex matches using a function that takes the match. Also makes it a lot easier to handle potential edge cases.

var html = jQuery("div.main_div").html();
console.log(html);
html = html.replace(/(\d*,\d+|\d*\.\d+|\d+)/ig, function(match) {
  return '<span style="background-color:yellow">' + match + '</span>';
});
console.log(html);
jQuery("div.main_div").html(html)
<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?</p>
</div>

The regex consists of 3 capture tokens:

\d*,\d+| matches any amount of digit followed by one . followed by at least one digit.

\d*\.\d+ matches any amount of digit followed by one , followed by at least one digit.

\d+ matches at least one digit.

Emil S. Jørgensen
  • 6,216
  • 1
  • 15
  • 28