Joshua Ohana
Joshua Ohana

Reputation: 6121

Node.js how to reply with RegEx object, Hapijs

I am trying to write an endpoint to return a set of regular expressions we use in the web app, to standardize them from the server side.

  const myRegExp: RegExp = /^\d{10}$/;
  return reply(myRegExp);

The problem is this reply comes in as {} when called

If I reply with a string, a number, an object, anything in the world... it comes through the reply as expected. Replying with a param of type RegExp, returns an empty object {}

How can I send back a raw RegExp regular expression in my Node / Hapi endpoint?

Yes, I know I can reply with myRegExp.source and then re-create with new RegExp(resp), but that seems silly unless I'm forced to.

Upvotes: 0

Views: 105

Answers (1)

metoikos
metoikos

Reputation: 1364

the reason hapi returns with an empty object is that the regexp object doesn't have any public properties. You can see that via your console.

> let x = new RegExp('/\d/')
> x
/\/d\//
> Object.keys(x)
[]

I think the right way to do it is that you can return myRegExp.source and then use it on your client-side code with new RegExp(resp) and it is not that silly.

Or you can just return your regexp definition as a string like

reply('/^\d{10}$/')

Then you can use it in your client code via new RegExp(resp)

I don't think it is possible directly returning evaluated regexp object from the server to the browser. Maybe you can do something like this;

reply(`const myRegExp = new RegExp(/^\d{10}$/);`).type("application/javascript");

Now you just loaded a javascript from the server, but I don't think it's useful.

Upvotes: 1

Related Questions