+ 1

JS can we add a variable inside a regex?

I just copied this snippets from stackoverflow for experimental code. And, it turns out I can’t put variables inside the “regex” thing. So, is there a way to put variables inside a regex value like this one, or is that not a thing? Var num = 8; txt= txt.match(/.{1,3}/g).join("-"); Replace 3, with num https://code.sololearn.com/WWc93fZ5ZllL/?ref=app

8th Jun 2020, 6:13 AM
Ginfio
Ginfio - avatar
2 Answers
+ 4
let three = 3; let re = new RegExp(`.{1, ${three}}`, 'g') // = /.{1,3}/g https://code.sololearn.com/Wog60qkMZTnt/?ref=app
8th Jun 2020, 6:30 AM
CalviŐ˛
CalviŐ˛ - avatar
+ 4
It's not reeeeeally a thing. There is the regex constructor which takes a string, so you can build your regex string which includes variables and then pass it to the Regex cosntructor. const regex = new RegExp(`.{1,${num}}`, "g"); But that is pretty ugly. It might be ok for one-off scripts, or in very select cases, but I don't feel good even typing it out. There is probably a better alternative!
8th Jun 2020, 6:30 AM
Schindlabua
Schindlabua - avatar