I have a basic Chrome App that I\'m building that constructs strings like this:
\"1 + 4 - 3 + -2\"
Seeing as you can\'t use eval()
Try this
var question = {
text: "1 + 4 - 3 + -2",
answer: eval(ans(question.text))
}
console.log('Text : '+question.text);
console.log('answer : '+question.answer);
Used String replace method
function ans(str){
var s = str.replace(/\s/g, '')
console.log('S : '+s);
return s;
}
Try modifying string to
"+1 +4 -3 -2"
utilizing String.prototype.split()
, Array.prototype.reduce()
, Number()
var question = {
text: "+1 +4 -3 -2",
answer: function() {
return this.text.split(" ")
.reduce(function(n, m) {
return Number(n) + Number(m)
})
}
};
console.log(question.answer())