Struggling with replacing text using jQuery and dealing with an array of search terms

Struggling to track down the issue of finding and replacing a text string, but encountering problems when trying to reference a variable. Oddly enough, everything seems to work perfectly if I manually input the number instead of using a variable.

An error message pops up saying: 'missing : after property id' whenever I attempt to refer to a variable:

var text = "section-1 section_1 section[1]";
var cloneCount = 1;
var cloneUp = 2;
var array = {
  "section-"+cloneCount:"section-"+cloneUp,
  "section_"+cloneCount:"section_"+cloneUp,
  "section\\["+cloneCount:"section\[" + cloneUp
};

for (var val in array) {
  text = text.replace(new RegExp(val, "gi"), array[val]);
  alert(text);
}

Any help or advice would be greatly appreciated!

Answer №1

The way you are initializing your array is incorrect and will likely result in a syntax error. Here is the correct approach:

var array = { };
array["section-"   + cloneCount] = "section-"  + cloneUp;
array["section_"   + cloneCount] = "section_"  + cloneUp;
array["section\\[" + cloneCount] = "section\[" + cloneUp;

If you need to use an expression to construct the key for an object literal, you must follow the syntax of o[...] = ... instead.

Check out this working example: http://jsfiddle.net/ambiguous/cDthk/

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

Having trouble aligning two contact forms side by side in the center

I've been researching CSS techniques for hours, experimenting with different methods to align them horizontally, but I'm struggling to achieve the desired result. Currently, I am delving into the world of UI/UX design and finding inspiration on ...

Actility's LoraWan platform integrated with Node-Red

I am currently working on learning how to implement an HTTP GET request for the Actility platform in Node-RED. However, I keep encountering an error 401 indicating that the authorization bearer is missing. This is how my setup looks: https://i.sstatic.ne ...

Update CSS using onChange event with an array of values

I'm currently working on an app that allows users to select a color scheme from a dropdown form. The hexidecimal values associated with the selected color scheme successfully populate specific text fields as intended. However, I am facing difficulty i ...

The Three.js environment experiences lag and a decrease in performance

In the threejs scene, there is a sphere geometry and a plane geometry. The sphere is textured with an image, while the plane geometry is textured with 2D text. The plane geometry is also attached with a click event. When clicking on the plane geometry, ...

Encountered an issue while building npm: "Error: Unable to locate module @restart/context

Lately, I've encountered an issue with npm build after upgrading to the latest version of react-bootstrap (1.0.0-beta.6). While creating an optimized production build... Failed to compile. Module not found: '@restart/context/forwardRef'. P ...

Form that updates the class attribute to 'active'

I have a webpage with 3 list items (<li>) and each has its own onclick() function. One of them is active by default. When a form on the page is submitted, I want it to switch the active class from the default item to one of the other two. How can thi ...

Extract the value from an array of objects

https://i.sstatic.net/fTShc.png Having some difficulty accessing the elements of an array. In order to assign a project name to a local variable projectName, I am seeking assistance with extracting the project name from the given JSON structure. Any hel ...

Breaking free from JavaScript snippet within a PHP function in WordPress

There seems to be an issue with a function within one of the PHP files on a WordPress website. It appears that there may be an error related to escaping multiple quotes and slashes. Here is the specific line of code causing trouble: echo '<script ...

Remove HTML element and launch in a separate browser tab while preserving styles

I am currently working on developing a single-page application with Polymer3 (Javascript ES6 with imports). One of the key functionalities of my application involves moving widgets to new browser windows, allowing users to spread them across multiple scree ...

Running a JavaScript animation within an Electron environment

My curiosity lies in developing man-machine interfaces using Electron. Currently, I am experimenting with a Star Trek life signs monitor demo. I came across this code that can be easily customized to create vertical and horizontal movements: http://jsfiddl ...

What are some ways to prevent manual page reloading in Node.js when using EJS?

Currently, I am utilizing Node as a server and frontend in EJS. My project involves working with socket.io, which is why it is essential that the page does not refresh manually. If a user attempts to reload the current page, the socket connection will be d ...

Create a unique onblur event listener for every element in a loop in Javascript

https://i.sstatic.net/tRYul.png I have added several items to a column in the database, but I am unsure of how to implement an onblur function for validation for each item within a loop. For example, if the NAME field is empty, I want to display an alert ...

Obtain the index for a data point using a SciPy sparse array

Currently, I am working on a CSR sparse array where there are many empty elements or cells. This array needs to support both forward and backward indexing. In other words, I should be able to provide two indices and receive the corresponding element (e.g., ...

Interfacing with the data fields of a native application using Node.js

After developing a native Android (Java) mobile application, I found myself needing to run a node.js server on the client side. Being new to this, I opted to utilize Node.js for Mobile Apps () in order to execute my index.js file. Following the provided in ...

Is there a clash between jquery_ujs and Kaminari AJAX functionality in Rails 4?

After some investigation, it seems that there is a conflict between jquery_ujs and Kaminari's AJAX support in my Rails 4 application. Within my application.js file, I have included the following: //= require jquery //= require jquery_ujs //= require ...

Creating Dynamic Input Binding in Vue.js with an Array of Computed Properties

Currently, I am faced with a situation where I need the v-model binding of an input field to be determined by the computed property's returned value. Take a look at the example provided below: <!DOCTYPE html> <html> <head> <scri ...

Identifying the Operating System and Applying the Appropriate Stylesheet

I am trying to detect the Windows operating system and assign a specific stylesheet for Windows only. Below is the code snippet I have been using: $(function() { if (navigator.appVersion.indexOf("Win")!=-1) { $(document ...

Nodejs cookie settings

I am currently working on a small petition project and I want to implement a feature where a user who signs the petition will have a cookie set so that when they try to access the page again, they are redirected to a "thanks page". If the user has not sign ...

Combining the powers of $.get and $.ready

Basically, I am facing an issue with my ajax call where sometimes it completes before the page is fully loaded. I attempted to use $( fn ) to wrap the callback function, but unfortunately, the callback does not trigger if the page is already loaded. Does a ...

How can I make TypeScript mimic the ability of JavaScript object wrappers to determine whether a primitive value has a particular "property"?

When using XMLValidator, the return value of .validate function can be either true or ValidationError, but this may not be entirely accurate (please refer to my update). The ValidationError object includes an err property. validate( xmlData: string, opti ...