例如,我有一个HTML元素(“总付款”),其中包含文本:“支付100.00英镑”。
我设法从中获得数字100,如下所示:
function getPaymentAmount(paymentAmount) {
var stringTotal = $("#paymentBtn").text();
var extractIntFromTotal = stringTotal.match(/\d+/)[0];
return extractIntFromTotal;
}
但是,我想取回十进制的100.00。我尝试添加到索引上,但这似乎不起作用。谁能帮忙吗?我对javascript非常陌生。
谢谢:)
关于使用split()
然后使用pop()
:
function getPaymentAmount(paymentAmount) {
var stringTotal = 'Pay £100.00';
var extractIntFromTotal = stringTotal.split('£').pop();
return extractIntFromTotal;
}
console.log(getPaymentAmount());
阅读问题的两句之间,看来实际的目标是从字符串中获取全价,包括十进制值。
最简单的方法是修改正则表达式以包括小数:
function getPaymentAmount(paymentAmount) {
var extractIntFromTotal = paymentAmount.match(/\d+\.\d{2}?/)[0];
return extractIntFromTotal;
}
var amt = getPaymentAmount('Pay £100.00');
console.log(amt);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
var text = "Pay £100.00";
var no = text.split("£")[1];
console.log(Math.floor(no));
尝试一下
var stringTotal = $("#paymentBtn").text();
var number = Number(stringTotal.replace(/[^0-9.-]+/g,""));
console.log(number);