Question

Coffeescript supports strings interpolation:

user = "world"
greeting = "Hello #{user}!"

Is it possible to use interpolation in regex just like in strings? E.g.

regex = /Hello #{user}/g

P.S. I know that I can use RegExp(greeting, 'g'), I just want a bit cleaner code.

Was it helpful?

Solution

Block Regular Expressions (Heregexes) support interpolation.

Block Regular Expressions

Similar to block strings and comments, CoffeeScript supports block regexes — extended regular expressions that ignore internal whitespace and can contain comments and interpolation. Modeled after Perl's /x modifier, CoffeeScript's block regexes are delimited by /// and go a long way towards making complex regular expressions readable.

This coffeescript code:

name="hello"
test=///#{name}///

compiles to

var name, test;

name = "hello";

test = RegExp("" + name);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top