2

Is there something like Perls /e modifier in JavaScript to integrate simple arithmetic like multiplication and addition to a regular expression that is evaluated with the RegExp object?

I want to transfer a pattern for URL generation which may includes concatenation, multiplication and division of strings and replaced integer variables that is more secure than to transfer and evaluate Javascript code.

Sebastian Barth
  • 4,079
  • 7
  • 40
  • 59
  • Nope: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#Parameters – Felix Kling Oct 14 '14 at 16:32
  • Is there maybe any other kind of pattern instead of regular expressions that allows such (nearly) limited operations? – Sebastian Barth Oct 14 '14 at 16:37
  • What you you try to do that's in need of a typical Perl `s///e` construct ? Can you show an example before / after ? Are you dynamically generating a regex, or modifying a regex ? –  Oct 14 '14 at 16:45
  • 1
    Actually what you're asking for is not more secure than transferring and evaluating javascript code. It IS transferring and evaluating JavaScript code albeit in a limited context. For something truly more secure you can combine @Sam's answer with a lookup table of different pre-defined functions to be called. For example you can send `{url: '...', processor: 'frobnicate'}` and validate that `frobnicate` is a valid processor then call it as your callback. – benrifkah Oct 14 '14 at 16:48

1 Answers1

7

What you desire is achieved by passing a callback function to .replace().


For example, in Perl:

my $result = '1 foo 2 bar 3' =~ s/\d+/ $& * 2 /erg;

And in Javascript:

var result = '1 foo 2 bar 3'.replace(/\d+/g, function(match) {
    return match * 2;
});

Both results will equal:

2 foo 4 bar 6

Reading the full documentation of .replace() will show extra parameters that can be passed to the callback function, including captured groups if necessary.

Sam
  • 20,096
  • 2
  • 45
  • 71
  • That's not a solution and does not answer the question. I have to transfer the arithmetic expression as well and I am looking for a more secure way than to send JavaScript - It would be a big security hole to execute JavaScript from an insecure source. – Sebastian Barth Oct 14 '14 at 16:41
  • 6
    @Ted Barth, This is a solution, and it does answer the question. This is exactly the same thing as `/e`. It's just a little shorter to type in Perl. – ikegami Oct 14 '14 at 17:28
  • 1
    The next time I will write a question five hundred words long, only to include all side-conditions in the same sentence - It's hard to write a question on SO that is interpreted as you want. The checkmark goes to you! :D – Sebastian Barth Oct 15 '14 at 06:54