Reputation: 108
I want to convert a string like this
var string = "3*v0-v1/v12"
to one like this using only one regex:
var result = "3*v[0]-v[1]*v[12]"
The tricky part is to add the numbers when adding the braces, something like:
var result = string.replace(/v\d{1,2}/g, /REGEX HERE/)
Upvotes: 0
Views: 1547
Reputation: 27282
This should do the trick:
var result = string.replace(/v(\d{1,2})/g, 'v[$1]');
The parentheses create a group, and the $1
is a backreference referring to that group:
Upvotes: 3