Search code examples
javascriptstringparseint

Javascript ParseInt with positive and negative numbers


String x = "{"val" : 34, "gain": -23}"

How can I get the positve or negative number out of string. I am trying:

x.split("gain")[1]; // returns something like " : -23

parseInt(x.split("gain")[1]); // returns NaN

Solution

  • Simplest thing you should do is parse JSON and access value

    let x = `{"val" : 34, "gain": -23}`
    
    console.log(JSON.parse(x).gain)

    You need to change the string to parse able state by removing anything which is not a valid number before parsing it with parseInt

    [^+-\d]+ 
    

    This above pattern means match anything except +, - or any digit and then we replace matched value by empty string

    let x = `{"val" : 34, "gain": -23}`.split("gain")[1]
    
    console.log(parseInt(x.replace(/[^+-\d]+/g,'')))