How to convert a list of strings to a list of regexes

I'm using Javascript and I'm importing data from a .txt file and I have all the elements from the .txt file in a list but I want to turn that list of strings into a list of regexes.

Lets say that for example I have the list: ["abc", "def", "ghi"]
I want to turn that into the list: [/abc/g, /def/g, /ghi/g]

I have figured out how to turn the entire list into a single regex, but my goal is to have each element from the list to strings correspond to an element in the list of regexes.

Here's what I have right now which turns everything from the list of strings into one regex:

var fs = require("fs");
var myList = fs.readFileSync("./files/mytextfile.txt", "utf-8")
myList = myList.split("\n");
var myListRegex = new RegExp(myList.join("\n"), 'g');

Using the same example list above, if I were to print myListRegex, it would result in the following:


when I want it to print this:

[/abc/g, /def/g, /ghi/g]

2 answers

  • answered 2021-05-15 02:37 Aadmaa

    const myList = ["abc", "def", "ghi"] const rez = myList.reduce((prev, curr) => [...prev, new RegExp(curr, 'g')], [] as RegExp[])

  • answered 2021-05-15 02:38 locrizak

    What you are doing now is splitting things, and then putting it back to how it was so this new RegExp(myList, 'g'); is identical to what you.

    What you need to do is split myList and map over it creating a RegExp in each index of the array.

    myList = myList.split("\n");
    var myListRegex = => new RegExp(expression, 'g'));