Javascript 如何从字符串中提取和计算数值
我需要一些帮助,根据分配给span文本标记的id从字符串中提取和计算数值。例如,我需要计算5%的折扣,并在另一个字段中显示正确的金额Javascript 如何从字符串中提取和计算数值,javascript,jquery,Javascript,Jquery,我需要一些帮助,根据分配给span文本标记的id从字符串中提取和计算数值。例如,我需要计算5%的折扣,并在另一个字段中显示正确的金额 <span id="discount">5% off<span> <span id="price">£2.75</span>/per month</span> $( document ).ready(function() { { var discount= "#discount";
<span id="discount">5% off<span>
<span id="price">£2.75</span>/per month</span>
$( document ).ready(function() { {
var discount= "#discount"; // a string
discount= discount.replace(/\D/g, ''); // a string of only digits, or the empty string
var discount= parseInt(discount, 10); // now it's a numeric value
var price= "#price"; // a string
price= price.replace(/\D/g, ''); // a string of only digits, or the empty string
var discount= parseInt(price, 10); // now it's a numeric value
var discountValue = (discount * price) / 100;
var newPrice= price + discount;
$("#price").text(newPrice);
})
5%折扣
每月2.75英镑
$(文档).ready(函数(){{
var discount=“#discount”//一个字符串
折扣=折扣。替换(//\D/g',);//一个只有数字的字符串或空字符串
var discount=parseInt(discount,10);//现在它是一个数值
var price=“#price”//一个字符串
price=price.replace(//\D/g',);//一个只有数字的字符串,或空字符串
var discount=parseInt(price,10);//现在它是一个数值
var贴现价值=(贴现*价格)/100;
var newPrice=价格+折扣;
$(“#价格”)。文本(新价格);
})
我不是Jquery和JavaScript的专家,因此请理解我有限的知识,如果有人能解释如何实现预期的解决方案,我将不胜感激。
谢谢假设您的输入(价格和折扣)是基于输入的条目,您可以使用提供的正则表达式从字符串中提取数字(假设一次只存在一组数字)
$(“#折扣”).text();
$(文档).ready(函数(){
var折扣=$(“#折扣”).text();//字符串
折扣=折扣。替换(/\D+/g');
//仅由数字组成的字符串或空字符串
var discount=parseInt(discount,10);//现在它是一个数值
var price=$(“#price”).text();//字符串
price=price.replace(//\D/g',);//一个只有数字的字符串,或空字符串
var discount=parseInt(price,10);//现在它是一个数值
var贴现价值=(贴现*价格)/100;
var newPrice=价格+折扣;
$(“#价格”)。文本(新价格);
})
五折
每月2.75英镑
我真的建议在业务逻辑中解决这个问题,而不是在前端使用jquery
$(function(){
var pattern = /[^0-9\.]/g;
var discount = parseFloat($('#discount').html().replace(pattern, ""));
var price = praseFloat($('#price').html().replace(pattern, ""));
var result = price - price * (discount/100);
console.log(result);
});
更新:
没有jquery:
(function(d){
var pattern = /[^0-9\.]/g;
var discount = parseFloat(d.querySelector('#discount').innerHTML.replace(pattern, ""));
var price = praseFloat(d.querySelector('#price').innerHTML.replace(pattern, ""));
var result = price - price * (discount/100);
console.log(result);
}(document);
为什么要使用自动执行的匿名函数呢?以保持全局作用域干净,并使那些变量的垃圾收集成为可能。一件事是,在
$(文档)上有一个额外的{
。就绪(函数(){
。您的折扣应该使用parseFloat而不是parseInt。更改var折扣=“#折扣”;by var discount=$(“#discount”).html();我认为您必须使用$(“#discount”).html()
来获取范围内的值,对于折扣值也是如此。您还需要执行price=price.replace('.'')
而不是discount=price.replace('/\D/g','')
因为正则表达式正在删除小数点,而您也在那里分配了错误的变量。嘿,迪内什,您的答案是非常完整的,我没有意识到我即将找到解决方案。非常感谢您的输入。
(function(d){
var pattern = /[^0-9\.]/g;
var discount = parseFloat(d.querySelector('#discount').innerHTML.replace(pattern, ""));
var price = praseFloat(d.querySelector('#price').innerHTML.replace(pattern, ""));
var result = price - price * (discount/100);
console.log(result);
}(document);