Jis*_*V S 0 html javascript css jquery
我有一个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>
Run Code Online (Sandbox Code Playgroud)
我只想为所有数字添加 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>
Run Code Online (Sandbox Code Playgroud)
我已经尝试过很多方法并检查此链接
但这只能选择第一个数字,只有我想选择 div 内的所有数字,如果 div 包含 20 个数字,我只需要添加跨度所有数字,这可能吗?最好的答案必须赞赏..
使用正则表达式匹配数字并换入 <span>
$(document).ready(function() {
$('.main_div p').each(function() {
$(this).html(
$(this).text().replace(/([0-9]+[.,][0-9]+|[0-9]+)/g, '<span>$1</span>')
);
})
});Run Code Online (Sandbox Code Playgroud)
span {
text-decoration: underline;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)