I want to parse some data that's in a string format. Anything enclosed in parenthesis in the string to parse should be replaced with itself run through a function. This is what I want:
function foo(str) {
return parseInt(str) + 1; // Example function, not actually what the function will be
}
function parse(str) {
// everything in str that is enclosed in parenthesis should be replaced with itself ran through foo();
// Example
// Input: "My name is foo and I am (0) year old."
// Output: "My name is foo and I am 1 year old."
// "(0)" has been replaced with the result of foo("0")
}
I have thought up a couple bad workarounds, but I want something more robust. For example:
function parse(str) {
// Input: "My name is foo and I am (0) year old."
str = str.replaceAll("(", "${foo('");
str = str.replaceAll(")", "')}");
str = "`" + str + "`"
// Here str will be "`My name is foo and I am ${foo(0)} year old.`"
// And I can use eval() or something to treat it like I've typed that
}
This, however, is kind of a bad way of doing it. EDIT: I tested it, it works, but it is quite vulnerable.
I can't think of anything else and I'm not very good with RegEx. (although I'd accept a solution using it)