Reputation: 141
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
Upvotes: 1
Views: 2184
Reputation: 2926
Don't you want to use JSON.parse(x)['gain']
?
let x = `{"val" : 34, "gain": -23}`
let gain = JSON.parse(x)['gain'];
console.log(gain);
Upvotes: 2
Reputation: 37755
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,'')))
Upvotes: 2
Reputation: 33
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
Replace : and trim string
let s = x.split("gain")[1].replace(":", "").trim();
parseInt(s);
Or
Change the x value to a proper object
let x = { val : 34, gain : - 23}
Then get gain as in x.gain
this will return - 23
Upvotes: 1