Javascript 定位并包装小数点后的第三位数字
我正在尝试制作一个脚本,该脚本只包含小数点后的第三位数字。其目的是为石油价格设定一美分的分数 即3.249输入输出Javascript 定位并包装小数点后的第三位数字,javascript,jquery,regex,Javascript,Jquery,Regex,我正在尝试制作一个脚本,该脚本只包含小数点后的第三位数字。其目的是为石油价格设定一美分的分数 即3.249输入输出 3.24<sup>9</sup> 3.249 到目前为止,我用的是小数点后的任何东西。例如,我可以跨越第一个、前2个或全部3个,但不能忽略前2个而只跨越第3个 <script> $(document).ready(function(){ $('.pricesup .maintext > span').html(
3.24<sup>9</sup>
3.249
到目前为止,我用的是小数点后的任何东西。例如,我可以跨越第一个、前2个或全部3个,但不能忽略前2个而只跨越第3个
<script>
$(document).ready(function(){
$('.pricesup .maintext > span').html(
$('.pricesup .maintext > span').html().replace(/\.\d{3}/,
function(a){
return '<sup>' + a + '</sup>';
})
);
});
</script>
$(文档).ready(函数(){
$('.pricesup.maintext>span').html(
$('.pricesup.maintext>span').html().replace(/\.\d{3}/,,
职能(a){
返回“+a+”;
})
);
});
我需要正则表达式/\d{3}/来选择最后一位数字或第三位小数。任何帮助都将不胜感激
JS小提琴:
为此,您需要几个捕获组:
<script>
$(document).ready(function(){
$('.pricesup .maintext > span').html(
$('.pricesup .maintext > span').html().replace(/(\.\d\d)(\d+)/g, "$1<sup>$2</sup>");
);
});
</script>
只是为了完整性:您不需要使用捕获组,但它可能是最干净的。如果继续使用以下函数,则无需执行此操作:
<script>
$(document).ready(function(){
$('.pricesup .maintext > span').html(
$('.pricesup .maintext > span').html().replace(/\.\d{3,}/g, function(m) {
return m.substring(0, 3) + "<sup>" + m.substring(3) + "</sup>";
});
);
});
</script>
$(文档).ready(函数(){
$('.pricesup.maintext>span').html(
$('.pricesup.maintext>span').html().replace(/\.\d{3,}/g,函数(m){
返回m.substring(0,3)+“”+m.substring(3)+“”;
});
);
});
rex匹配一个点,后跟三个或更多数字,然后将匹配的字符串切碎
我会使用上面的第一个解决方案,即FWIW,使用捕获组和占位符。既然其他人已经给出了答案,我会对您最初的努力给出一个提示作为注释:
{3}
是一个量词;射程。您告诉它匹配前面的3个字符(\d
),而不是第三个\d
。因此,提供的解决方案表明,您必须首先匹配前两位数字,然后匹配第三位数字。
<script>
$(document).ready(function(){
$('.pricesup .maintext > span').html(
$('.pricesup .maintext > span').html().replace(/\.\d{3,}/g, function(m) {
return m.substring(0, 3) + "<sup>" + m.substring(3) + "</sup>";
});
);
});
</script>