Reputation: 1
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:
/abc
def
ghi/g
when I want it to print this:
[/abc/g, /def/g, /ghi/g]
Upvotes: 0
Views: 237
Reputation: 12279
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 = myList.map((expression) => new RegExp(expression, 'g'));
Upvotes: 1
Reputation: 932
const myList = ["abc", "def", "ghi"] const rez = myList.reduce((prev, curr) => [...prev, new RegExp(curr, 'g')], [] as RegExp[])
Upvotes: 0