如何找到div中的所有数字并使用jquery添加<span> </span>标记?

时间:2016-10-26 06:45:02

标签: javascript jquery html css

我有DOM这样的

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

我只想为所有数字添加span标记,例如

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

我已尝试过这样的方法并检查此链接

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

但这只能选择第一个数字我只想选择div中的所有数字,如果div包含20个数字我只需要添加span所有数字,这可能吗?必须欣赏最佳答案..

2 个答案:

答案 0 :(得分:4)

使用正则表达式匹配数字并在<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>

答案 1 :(得分:3)

在div html(或text上使用正则表达式,如果你害怕混淆html)。

使用匹配的函数替换正则表达式匹配项。还可以更轻松地处理潜在的边缘情况。

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>

正则表达式由3个捕获令牌组成:

\d*,\d+|匹配任意数量的digit,后跟一个.,后跟至少一个digit

\d*\.\d+匹配任意数量的digit,后跟一个,,后跟至少一个digit

\d+至少匹配一个digit