简体   繁体   中英

How to split $ from javascript value

I want to split the $ symbol from i variable and display the value like 20 not like ,20 .

The code I use for this:

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

How do I split the value without comma?

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

JS Fiddle demo .

Edited (belatedly) to address the problems of that particular regular expression removing any . or , characters (to denote decimals):

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

JS Fiddle demo .

References:

Try this:

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);

Don't parse it just perform the addition directly:

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)

Also if you have to replace some character in a string use replace():

i = i.replace(/\$/g,'')

check this it work fine Demo

var i = "$20";
var j = "10";
var values = i.split('$');
var v = values[1];
var sum = parseInt(v) + parseInt(j);
alert(sum);

Try

var i = "$20"
   ,j = "10"
   ,sum = +j + +i.slice(1);
//=> sum = 30

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM