Unicode regex \p{L} not working in NodeJS

Viewed 1687

I am trying to make the following unicode regular expression work in nodejs, but all I get is an invalid escape error. I can't figure out, what to escape here or if this for some reason doesn't work at all in node. This is my original regex:

/([\p{L}|\-]+)/ug

If I escape the \p like \\p, the regex doesn't work anymore (outputs only p,L and -)

This works in chrome, so it should work in node somehow too, right? Thanks for your help.

var str = "thÛs Ís spå-rtÅ!";

console.log(str.match(/([\p{L}|\-]+)/ug))

2 Answers

A quick look through the nodejs changelog revealed this PR:

https://github.com/nodejs/node/pull/19052

which most notably states:

RegExp Unicode Property Escapes are at stage 4 and will be included in ES2018. They are available since V8 6.4 without a flag so they will be unflagged in Node.js v10. They are also available under the --harmony_regexp_property flag in Node.js v6-v9 and under the --harmony flag in Node.js v8-v9.

So by the look of it, if you are on node v6-v9, you can enable this feature by running node with a flag. For example, this works for me on node v8.11.3:

node --harmony regex-test.js

(where regex-test.js contains your sample code). Running this without the flag gives your Invalid escape error.

If you can update your node version to v10+, no flag is needed.

If you are going to use --harmony flag please consider this

As mentioned in the Node Documentation, --harmony flag enables the non-stable but to be soon stable features of ES6

The current behaviour of the --harmony flag on Node.js is to enable staged features only. After all, it is now a synonym of --es_staging. As mentioned above, these are completed features that have not been considered stable yet. If you want to play safe, especially on production environments, consider removing this runtime flag until it ships by default on V8 and, consequently, on Node.js. If you keep this enabled, you should be prepared for further Node.js upgrades to break your code if V8 changes their semantics to more closely follow the standard.

here is the link for that https://nodejs.org/en/docs/es6/#:~:text=The%20current%20behaviour%20of%20the,to%20enable%20staged%20features%20only.&text=If%20you%20want%20to%20play,js.

Related