1

我想从中拆分$符号i variable并显示类似于20not like的值,20

我用于此的代码:

<script>
    var i = "$20";
    var j= "10";
    var values=i.split('$');
    var v = values;
    var sum=parseInt(v)+j;
    document.write(sum);
</script>

如何在没有逗号的情况下拆分值?

4

5 回答 5

3
var i = "$20",
    j= "10",
    v = i.replace(/\D/g,''),
    sum = parseInt(v, 10)+parseInt(j, 10);
document.getElementById('output').textContent = sum;

JS 小提琴演示

编辑(迟来)以解决该特定正则表达式删除任何.,字符(表示小数)的问题:

var i = "$20.23",
    j= "10",
    v = i.replace(/[$£€]/g,''),
    sum = parseFloat(v) + parseInt(j, 10);
document.getElementById('output').textContent = sum;

JS 小提琴演示

参考:

于 2013-10-04T12:40:46.647 回答
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);
于 2013-10-04T12:40:14.363 回答
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,'')
于 2013-10-04T12:42:23.297 回答
0

检查这个它工作正常演示

var i = "$20";
var j = "10";
var values = i.split('$');
var v = values[1];
var sum = parseInt(v) + parseInt(j);
alert(sum);
于 2013-10-04T12:42:33.230 回答
0

尝试

var i = "$20"
   ,j = "10"
   ,sum = +j + +i.slice(1);
//=> sum = 30
于 2013-10-04T12:44:54.497 回答