How can I concatenate regex literals in JavaScript? Ask Question

How can I concatenate regex literals in JavaScript? Ask Question

Is it possible to do something like this?

var pattern = /some regex segment/ + /* comment here */
    /another segment/;

Or do I have to use new RegExp() syntax and concatenate a string? I'd prefer to use the literal as the code is both more self-evident and concise.

ベストアンサー1

Here is how to create a regular expression without using the regular expression literal syntax. This lets you do arbitrary string manipulation before it becomes a regular expression object:

var segment_part = "some bit of the regexp";
var pattern = new RegExp("some regex segment" + /*comment here */
              segment_part + /* that was defined just now */
              "another segment");

If you have two regular expression literals, you can in fact concatenate them using this technique:

var regex1 = /foo/g;
var regex2 = /bar/y;
var flags = (regex1.flags + regex2.flags).split("").sort().join("").replace(/(.)(?=.*\1)/g, "");
var regex3 = new RegExp(regex1.source + regex2.source, flags);
// regex3 is now /foobar/gy

It's just more wordy than just having expression one and two being literal strings instead of literal regular expressions.

おすすめ記事