Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript: run specific parts of strings through a function

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I can’t think of anything else and I’m not very good with RegEx. (although I’d accept a solution using it)

>Solution :

You could used a full matching pattern, and wrap the resulting string in back-ticks so it’s evaluated as a string literal.

const foo = (value) => +value + 1;

const parse = (str) =>
  '`' +
  str.replace(/\((\w+)\)/g, (_, v) => `\${foo(${v})}`) +
  '`';

// Source: https://stackoverflow.com/a/29182787/1762224
console.log(eval(parse('My name is foo and I am (0) year old.')));

The only problem with this is that the pattern to match between the parenthesis seems to be any kind of value. This could pose problems down the road. Just tweak the regular expression as-needed.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading