Converting a JavaScript array of strings into a regular expression literal

Here is a live example you can check out: http://jsfiddle.net/R7KuK/

In an attempt to create an array of full regular expressions with regex delimiters and set flags, I've noticed that the RegExp object is interpreting given strings as strings rather than regular expressions.

  var regex = "/wolves/i"

as opposed to

  var regex = /wolves/i

So, my main question is: How can I convert string-based regular expressions into actual regular expressions?


UPDATE: Thanks to the explanation provided by Felix King, it was clarified to me that

var array = ["/wolves/i", "/Duck/"];

can be safely converted to:

var array = [/wolves/i, /Duck/];

Answer №1

Check out this alternative solution:

let splitRegex = regex.split( '/' );
let customRegex = new RegExp( splitRegex[1], splitRegex[2] );

Alternatively, you can try:

let matchRegex = regex.match( /^\/(.*)\/([^\/]*)$/ );
let customRegex = new RegExp( matchRegex[1], matchRegex[2] );

This second option is better as it handles cases where the regex contains '/'. 😉

Answer №2

taken directly from this source:

To form a regular expression from a string, utilize the RegExp object constructor:

var pattern = new RegExp("x|y", "g");
// equivalent to
var pattern = /x|y/g;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating an animated link with a dynamic underline featuring a trio of vibrant colors

I'm having trouble figuring out how to animate my links on hover with 3 different colors. I attempted using the linear-gradient property but it doesn't seem to be working. Any suggestions on how to proceed? Below is an example of what I'm a ...

Guide to attaching a page content button to a fixed header

I am currently developing a webpage with a sticky header, and I want to include an animated button that moves onto the header when scrolled past. You can check out my code snippet here: https://jsfiddle.net/ykL50pjf/ The specific ID for the button is #t ...

Each time the state changes, the array of components is reset

I'm working on a form to create training programs that display a week, starting with an array of all the days. The rendered day depends on the current day (state). The issue is that every time I switch the current day, such as clicking on a different ...

What is the best method to convert a variable array into a string array using jQuery in the context

I've been working with this jQuery code snippet: function extractParameter() { var values = []; $("input[name='SelectedServiceTypes']:checked").each(function (i) { values.push($(this).val()); }); if (values.length == ...

Changing a date format in typescript: Here is how you can easily convert a date from one

Using React with Typescript: I am currently working with a date picker from material-ui version 5. The date picker requires the date value to be in the format "yyyy-MM-dd". However, the API returns a Date object in the format "2022-01-12T00:00:00.000+00:0 ...

Showcasing an image stored in an HTML file on a Vue.js webpage

I'm currently facing an issue with displaying a local image saved in an HTML file on my Vue.js page. I attempted to store the content of the HTML file into a variable using the code below: computed: { compiledHtml: function() { return this.a ...

When passing the value of "undefined" into a function, keep in mind that the function must be declared in a separate JavaScript file. This

I'm facing an issue with my JavaScript code. I have a file named test.js that contains a function like this: export const a = (data) => { console.log(data) } In addition, I have a functional component called File.js as shown below: import Reac ...

How to assign the current item in a foreach loop to an array in PowerShell

Hi there and thanks for checking this out. I need to go through each item in a folder and gather file names and sizes that meet certain criteria to put into an array for an email. Specifically, I only want to include files with a .txt extension. Currently, ...

Is it possible to reveal a concealed element or modify the functionality of a hyperlink?

I have a link in the navigation that includes an animated icon of a + turning into an x. When the icon is in the x state, I want users to be able to close it by clicking on the icon or text. However, I am unsure of the best way to approach this. One op ...

Incorporation of a jQuery function

I'm encountering an issue with importing JavaScript functions, specifically with gmaps.js. I have included this library in my web pages and have a main.js file where I call the script in the following manner: var map = new GMaps({ el: '#map& ...

The 'presenceUpdate' event in Discord.js seems to be inactive and not triggering as expected

I have a unique scenario with a "Special User" that I fetch using 'Client.users.fetch(Special User's ID)'. This user has two event listeners attached to it, 'message' and 'presenceUpdate'. The message event listener funct ...

Extracting HTML elements between tags in Node.js is a common task faced

Imagine a scenario where I have a website with the following structured HTML source code: <html> <head> .... <table id="xxx"> <tr> .. </table> I have managed to remove all the HTML tags using a library. Can you suggest w ...

Having issues with setInterval function when restricting the number of MySQL rows

My simple chat application with setInterval is experiencing an issue when I try to limit the number of rows displayed from the database. Currently, the chat loads everything from if($q == "load") { and functions correctly. However, when I attempt ...

A guide to creating a reference between two tables using the hasOne method in sequelize.js

After generating 3 models using sequelize-auto, let's take a look at them: sequelize.define('users', { id: { type: DataTypes.INTEGER, allowNull: false, primaryKey: true, autoIncrement: ...

Unable to deactivate button within component using setState is ineffective

Once the button within the RecipeListItem component is clicked and the handleFavorites function has been triggered, I want the button to become DISABLED. What am I missing in my logic? Because this code isn't functioning as expected... Child compone ...

TypeScript Compile Error: The property is not available in the 'IStateParamsService' type

My client project heavily utilizes TypeScript. Currently, I am encountering a technical issue. Within my HTML code, I have an anchor tag as shown below: <a class="btn btn-default mrm" ui-sref="course-detail({courseId: '{{c.Id}}'})">Detail ...

JavaScript: Choosing an element by class within the current row using jQuery

One of my tasks involves generating a table with values fetched from a database. The column totals are displayed at the end of the table. I am looking to provide users with the option to remove specific rows they do not wish to see, and have the total auto ...

Exploring the World of Node.js Background Operations

What is the best approach for handling background processes in a NodeJS application? Situation: When a user posts something to an app, I need to process data, fetch additional information from external sources, etc. Due to the time-consuming nature of the ...

How can we convert multiple arrays into a single JSON object?

I have multiple arrays like the ones shown below: var a=[1,2,3,4,5,6,7,8,9]; var b=["a","b","c","d","e","f","g","h","i","j"]; However, I need to convert these arrays into an array object structured like this: ab=[ ["1","a"], ...

vertical lines alongside the y-axis in a d3 bar graph

https://jsfiddle.net/betasquirrel/pnyn7vzj/1/ showcases the method for adding horizontal lines along the y axis in this plunkr. I attempted to implement the following CSS code: .axis path, .axis line { fill: none; stroke: #000; } I am lo ...