1

I am attempting to generate some code using escodegen's .generate() function which gives me a string.

Unfortunately it does not remove completely the semi-colons (only on blocks of code), which is what I need it to do get rid of them myself. So I am using the the .replace() function , however the semi-colons are not removed for some reason.

Here is what I currently have:

  generatedCode = escodegen.generate(esprima.parseModule(code), escodegenOptions)
  const cleanGeneratedCode = generatedFile.replace(';', '')
  console.log('cleanGeneratedCode ', cleanGeneratedCode) // string stays the exact same.

Am I doing something wrong or missing something perhaps?

TylerH
  • 20,799
  • 66
  • 75
  • 101
theJuls
  • 6,788
  • 14
  • 73
  • 160
  • Chances are it is removing a single semicolon. Instead of using a substring, try `generatedFile.replace(/;/g, '')`. – c1moore Oct 21 '17 at 20:21
  • Thanks! That was exactly what I needed (should have known better...). Put that as an answer so that I can mark it as the resolution for the problem :) – theJuls Oct 21 '17 at 20:25
  • use RegExp for replace all : generatedFile.replace(new RegExp(';', 'g'), ''); – mscdeveloper Oct 21 '17 at 20:27
  • @mscdeveloper I had never seen that before. It sure makes it easier for future use when a specific character all over the string. Thanks for the advice! – theJuls Oct 21 '17 at 20:48

1 Answers1

2

As per MDN, if you provide a substring instead of a regex

It is treated as a verbatim string and is not interpreted as a regular expression. Only the first occurrence will be replaced.

So, the output probably isn't exactly the same as the code generated, but rather the first semicolon has been removed. To remedy this, simply use a regex with the "global" flag (g). An example:

const cleanGenereatedCode = escodegen.generate(esprima.parseModule(code), escodegenOptions).replace(/;/g, '');
console.log('Clean generated code: ', cleanGeneratedCode);
c1moore
  • 1,827
  • 17
  • 27