Why isn't .replace() working on a large generated string from escodege.generate()?

52 views Asked by At

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?

1

There are 1 answers

0
c1moore On BEST ANSWER

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);