askovpen
askovpen

Reputation: 2494

How to use variable 'object' in regex?

vers={jquery:"2.1.1"};
...
.pipe(replace(/src=".*\/(.*).js"/g, 'src="js/$1.min.js?ver='+vers["$1"]+'"'))
...

Why '...src="js/jquery.min.js?ver=undefined"...'? And how to make rightly?

Upvotes: 0

Views: 66

Answers (2)

epascarello
epascarello

Reputation: 207521

It fails because you are actually passing in $1, not the string value. You need to use the function

str.replace(YourRegExp, function(fullmatch, group1) { return 'src="js/' + group1 + '.min.js?ver='+vers[group1]+'"'; });

Upvotes: 2

Dancrumb
Dancrumb

Reputation: 27539

The expression 'src="js/$1.min.js?ver='+vers["$1"]+'"' is evaluated before it is passed into replace. As such, "$1" has no special meaning and is treated as that literal string. This means you're trying to resolve the "$1" of the vers object and, thus, getting undefined.

replace can take a function as its second parameter which you can use to identify the correct vers value at runtime and replace it as needed.

Upvotes: 1

Related Questions