我想将$
符号与i variable
分开,并显示20
之类的值,而不是,20
。
我用于此的代码:
<script>
var i = "$20";
var j= "10";
var values=i.split('$');
var v = values;
var sum=parseInt(v)+j;
document.write(sum);
</script>
如何在不使用逗号的情况下拆分值?
答案 0 :(得分:3)
var i = "$20",
j= "10",
v = i.replace(/\D/g,''),
sum = parseInt(v, 10)+parseInt(j, 10);
document.getElementById('output').textContent = sum;
编辑(姗姗来迟)解决删除任何.
或,
字符(表示小数)的特定正则表达式的问题:
var i = "$20.23",
j= "10",
v = i.replace(/[$£€]/g,''),
sum = parseFloat(v) + parseInt(j, 10);
document.getElementById('output').textContent = sum;
参考文献:
答案 1 :(得分:1)
试试这个:
var i = "$20";
var j = "10";
var values = i.split('$'); // Creates an array like ["", "20"]
var v = values[1]; // Get the 2nd element in the array after split
var sum = parseInt(v, 10) + parseInt(j, 10);
console.log(sum);
答案 2 :(得分:1)
不解析它只是直接执行添加:
var i = 20;
var j = 10;
var sum = i + j; // use parseInt() if it's defined as a string - see below
// var i = "$20".replace(/\$/g,'');
// var j = "30";
// var sum = parseInt(i) + parseInt(j)
此外,如果您必须替换字符串中的某些字符,请使用replace():
i = i.replace(/\$/g,'')
答案 3 :(得分:0)
检查一下它是否正常Demo
var i = "$20";
var j = "10";
var values = i.split('$');
var v = values[1];
var sum = parseInt(v) + parseInt(j);
alert(sum);
答案 4 :(得分:0)
尝试
var i = "$20"
,j = "10"
,sum = +j + +i.slice(1);
//=> sum = 30