Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coffeescript Regex interpolation

Tags:

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.

like image 952
Yossi Avatar asked May 13 '14 12:05

Yossi


1 Answers

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);
like image 65
edi9999 Avatar answered Sep 16 '22 22:09

edi9999