Search code examples
javajavascriptregexmozillarhino

How does JavaScript identify unquoted plain expression as RegExp Object?


Considering the JavaScript RegExp and its declaration process you may declare a regular expression in JavaScript on the fly

var exp_blood = /^[A|a|B|b|AB|ab|O|o]{1,2}[+-]{1}$/;

or initialize it with its constructor RegExp

var exp_blood = new RegExp("/^[A|a|B|b|AB|ab|O|o]{1,2}[+-]{1}$/");

Considering this scenario I would like to build an object on the fly without initializing any constructor explicitly or with a finite/unique expression. I would like to declare an object without using its Constructor named HL7V2. I could create an object with its Constructor. For example:

var hl7 = new HL7V2("MSH|^~\&|SENDERAPP|SENDERFAC|COVCDR|COVCDR|20130212221503||ORU^R01|1676326503009050|P|2.6");

But my goal is to instantiate it on the fly like RegExp in JavaScript

var hl7 = MSH|^~\&|SENDERAPP|SENDERFAC|COVCDR|COVCDR|20130212221503||ORU^R01|1676326503009050|P|2.6;

Is it possible or any suggestion?


Solution

  • The RegExp syntax is one of a few literal syntaxes built in to the language which allow you to create objects of a certain type using a special syntax (other types that can be built using literal syntaxes include strings and arrays).

    These syntaxes are features of the language, and you can't add new ones for your own types.

    It is possible to create objects using the object literal syntax, but it sounds like you want to create a specific type of object, which this won't help you with - I don't think what you want to do is possible.