1

I have a regex that uses lookbehind:

(?<!\S)\'\S(.*?)\S\'(?!\S)

It's an ES2018 feature.

I'm also using Typescript, so I run my code with ts-node.

When running the code, I got this error:

SyntaxError: Invalid regular expression: /(?<!\S)\'\S(.*?)\S\'(?!\S)/:
Invalid group

Doing this, however, runs the code successfully:

node --harmony script.js

I tried adding this to my tsconfig.json:

{
  "compilerOptions": {
    "target": "es6",
    "lib": [
      "ES2018" // I also tried es2018. No luck.
    ],
    "module": "commonjs",
    "outDir": "out",
    "sourceMap": true
  }
}

But I'm getting the same error.

Any advice?

Note: I updated node to version 13 via nvm. Doing node script.js works, but not ts-node script.ts. I already have the latest version of ts-node, so I'm not sure what to do.

alexchenco
  • 53,565
  • 76
  • 241
  • 413
  • Running `ts-node src/index.ts` where `index.ts` is `const pattern = /(?<!\S)\'\S(.*?)\S\'(?!\S)/; console.log(pattern.test('foo'));` and my tsconfig.json is identical to yours results in the code running with no errors, for me – CertainPerformance Feb 01 '20 at 07:18
  • @CertainPerformance Hm, maybe the problem is my Node version? Mine is v8.9.0. (I don't think the issue is TypeScript or ts-node, because I installed them recently. – alexchenco Feb 01 '20 at 07:24
  • @CertainPerformance I installed the lastest node version via nvm. Same error. – alexchenco Feb 01 '20 at 07:43

1 Answers1

2

Lookbehind was first introduced to Node sometime in version 8, but since (back then) it was an experimental feature, it required the --harmony flag (which enables experimental features, such as new syntax, which are not considered 100% reliable and stable yet). Getting ts-node to run node with the harmony flag is a bit ugly - you have to run native Node and have it preload ts-node, something like:

node --harmony -r ts-node/register index.ts

(make sure ts-node is installed locally)

Lookbehind graduated out of Harmony in node 10, so you'll be able to run lookbehind without the harmony flag if you update Node to version 10. (It looks like version 9.11.2 also supports it)

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Weird. I switched to Node 13 via nvm and installed ts-node again: `npm install ts-node -g /home/alex/.nvm/versions/node/v13.7.0/bin/ts-node` I'm getting the same error. – alexchenco Feb 01 '20 at 07:44
  • The global flag might be causing the issue if you also have a local installation - try installing it locally too – CertainPerformance Feb 01 '20 at 07:48
  • Ah, doing node `script.js` works. So the problem is `ts-node` ... And the harmony flag doesn't work with `ts-node`. I wonder how to fix that. – alexchenco Feb 01 '20 at 07:49
  • Never mind. I updated everything, and now everything works. Thanks. – alexchenco Feb 01 '20 at 08:02