How come my JavaScript regular expression doesn't function properly when applied to elements in an array?

let numbers = new Array('1','2','3');
let letters = new Array('a','b','c');
let length = numbers.length;
let str = 'abcdefgabcdefg';

for (let i=0; i<length; i++) {
   let regex = new RegExp(numbers[i],'g');
   str = str.replace(letters[i], regex);
}

alert(str);

The desired output is 123defg123defg. However, the actual output is /1/g/2/g/3/gdefgabcdefg.

Answer №1

Your approach needs adjustment because the goal is to globally replace instances of array y with instances of x. To achieve this, consider modifying your code as shown below:

for (let index=0;index<iLen;index++) {
   let regex = new RegExp(y[index],'g'); //create a regular expression for global y[i]
   s = s.replace(regex, x[index]); //replace all instances of y[i] with x[i] globally
}

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

Substitutions not functional when using SendGrid in conjunction with Firebase functions

I'm encountering difficulties when trying to include substitutions data in emails sent from Sendgrid using Firebase Cloud Functions. Here's my function exports.firestoreEmail = functions.firestore .document('users/{id}') .onCreate(s ...

When attempting to display the image file path using the JavaScript API Notification in Angular, there is a challenge in

Hello fellow developers, I am currently facing an issue with retrieving a local image from my assets folder and displaying it on a new Notification object generated by the Web Notification API. I have an image in my assets folder with a .jpeg extension. ...

Anticipated request for spy navigation with path '/members' was expected, but unfortunately was not triggered

I am facing an issue with a service method that performs an HTTP delete operation. The expected behavior is that upon successful deletion, the page should be redirected to another location. However, during testing, I noticed that the router navigation func ...

What is the best way to handle errors generated by my jsdom.jqueryify callback function?

When running this code in node.js, the output is a stack trace of an error that occurs on line 9. Surprisingly, the error on line 7 seems to be 'absorbed' by Node. Even when wrapped in a try/catch statement, the detailed stack trace output is not ...

How can I position two divs side by side within an Appbar?

I would like the entire Container to be in a single row, with the Typography centered as it already is, and the toggle-container to float to the right <AppBar className={styles.AppBar}> <Toolbar> <Container> ...

Guide on sending a message to a specific channel using Discord.js version 13 with TypeScript

After recently diving into TypeScript and seeing that Discord.js has made the move to v13, I have encountered an issue with sending messages to a specific channel using a Channel ID. Below is the code snippet I am currently using: // Define Channel ID cons ...

Building a contact form in Angular and sending emails with Nodemailer

Currently, I am in the process of setting up a contact form for my website. Since I am utilizing a MEAN stack, it made sense to incorporate the nodemailer module for sending emails. In order to handle this functionality, I have established an endpoint &ap ...

Dealing with images on my live React application

For managing static images in my react app, I have integrated cloudinary as a CDN service. Can anyone suggest a seamless way to switch between using local image folders during development and switching to the CDN URL for production efficiently? ...

Is it possible to ensure a div occupies all available space within a column using the vh-100 class in bootstrap?

In the <div class="bg-primary"></div> element, I'm trying to make it take up the remaining empty space without exceeding the vh-100. I've experimented with various solutions but haven't been able to find a fix yet. b ...

updating the HTML DOM elements using JavaScript is not yielding any response

One way that I am trying to change the background of a div is by using a function. Below is an example of the html code I am working with: $scope.Background = 'img/seg5en.png'; document.getElementById("Bstyle").style.background = "url("+$scope.B ...

Ways to retrieve every element inside a specific div container

Is there a way to select all elements inside a div except for specific ones? For example, consider the following structure: <div id="abc"> <div class="def"> sagar patil</div> <div class="pqr"> patil</div& ...

What is the difference between using 'classes' and 'className' in Material UI?

I find myself a bit perplexed about these two properties. Let's say I have, const useStyles = makeStyles(() => ({ style: { width: 600, height: 400, }, })); With this, I can use, const classes = useStyles(); <SomeComponent classNa ...

Sending values to URL using the <a> tag in HTML

I currently have the selected language stored in a variable (var lan= urlParam('language')). I am trying to pass this language as a parameter (without PHP) in a URL within an "a" tag, like so: <a href="http://hotelscombined.sitewish.gr/HotelN ...

Inspecting Mapped Data in React using the Console

For some reason, I am unable to console.log any selection when using onClick in this React component. My goal is to achieve the following functionality. https://codesandbox.io/s/great-ardinghelli-6seko?file=/src/demoComponent.jsx I have successfully fetc ...

button that smooth slides out using jquery

Here is the source code for a jQuery slideout: jQuery(function($) { $('#slideClick').toggle(function() { $(this).parent().animate({left:'0px'}, {queue:false, duration: 500}); }, function() { $(t ...

"Pressing the 'back' button on your browser takes

Is there a way to navigate back to the main page by clicking on an image? After selecting First, Picture1 will be shown. How can I go back to the selection page for further choices? <a href="picture1.jpg"> <h3>First</h3></a> <a ...

Having issues with displaying a pie chart in a React application using Chart.js

I am currently experiencing a problem with displaying a pie chart in a React component using the react-chartjs-2 library and Chart.js. The data for the chart is retrieved from an API, and I expect the chart to appear once the data is ready. However, despit ...

The onprogress event for the XMLHttpRequest object threw an error due to an Uncaught SyntaxError, indicating

I have implemented an ajax function successfully However, I am facing an issue where when using onprogress, I sometimes receive incomplete HTML response and the console displays Uncaught SyntaxError: Invalid or unexpected token but the function still cont ...

Refresh the database values every five minutes

I am currently developing a web application that assigns users a ranking based on their activity on Twitter and on my website. For this reason, I want to update their rank every five minutes by retrieving their latest Twitter activity and updating it in m ...

What methods can I use to adjust the selected option according to the value in the database?

To introduce you to my work, I have a table filled with data from a database that functions as a CRUD - Create, Read, Update, Delete table. Within this table, there is a column where EDIT and DELETE buttons are located. Clicking on the EDIT button trigger ...