0

In JavaScript, I am trying to match all occurrences of the following

initChart('something');
initMap('another');

initChart();
initMap();

UNLESS it is preceded by the word 'function', meaning, do not match

function initChart(param) { ... }
function initMap(param) { ... }

Basically I need to strip out all occurrences that invoke the function, while leaving the function definition in tact. I got this far

/init.*(.*)/i

This is what my script looks like to strip out matches:

var scriptRegex = /init.*(.*)/i;
while (scriptRegex.test(responseHTML)) {
   responseHTML = responseHTML.replace(scriptRegex, "");
}

But I'm stuck at how to tell it "only if it is NOT preceded by the word 'function'

TetraDev
  • 16,074
  • 6
  • 60
  • 61

1 Answers1

1

The problem is that Javascript regex doesn't have the lookbehind feature, so you can't test if there's the "function" keyword before only with regex. (and most of the time, when this feature is available, the subpattern inside the lookbehind must have a fixed width, this means that you can't test cases where the function name is separated from the "function" keyword with an unknown number of spaces.)

So you need a workaround. You can for example use capture groups to know if there's a keyword function before with this kind of pattern:

/\b(?:(function)\s+)?(init\w*)\s*\(/

if the first capture group contains "function" you can exclude the match.

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
  • I see what you're saying. How would I tell my script to exclude the first match, but include the second match? I updated my question with my code that I use to strip out matches. – TetraDev Jan 11 '17 at 23:19
  • @TetraDev; You can't tell anything to your regex. Test the first capture group and if it doesn't contain "function", takes the second capture group. If you need the pattern for a replacement, use a function as replacement to do that. – Casimir et Hippolyte Jan 11 '17 at 23:23