Given a string:
var str1 = \"25*5+5*7\";
Without using eval
or the constructor function in JavaScript, how would I be able to
You can create a new script:
function parse(str) {
var s = document.createElement('script');
s.text = "window.result = " + str;
document.body.appendChild(s); // Run script
document.body.removeChild(s); // Clean up
return result; // Return the result
}
document.body.innerHTML = parse("5*5+5*5");
Or use event handler content attributes:
function parse(str) {
var el = document.createElement('div');
el.setAttribute('onclick', "this.result = " + str);
el.onclick(); // Run script
return el.result; // Return the result
}
document.body.innerHTML = parse("5*5+5*5");
Note these approaches are unsafe and as evil as eval
but uglier. So I don't recommend them.