Is there a way to substitute one substring with another substring within the values of an array's objects using Javascript?

var temp = [
  {
    text:'some text and then % sign and then, again % sign',
    link: 'another text with %',
  },
 ];

I need to modify the temp array of objects to replace all occurrences of % with \%. How can this be achieved?

Desired Output:

var temp = [
  {
    text:'some text and then \% sign and then, again \% sign',
    link: 'another text with \%',
  },
 ];

I have attempted two different methods, but neither one worked as expected:

First approach involves using a for loop:

for(let i = 0; i<temp.length; i++) {
    temp[i].text = temp[i].text.replace(/%/g, '\\%');
    temp[i].link = temp[i].link.replace(/%/g, '\\%');
}

Output: The result included double backslashes.

[
    {
        text: 'some text and then \\% sign and then, again \\% sign',
        link: 'another text with \\%'
    }
]

Second method involves using JSON.parse and JSON.stringify:

temp = JSON.parse(
    JSON.stringify(temp).replace(/%/g, '\\%')
);

Output: It returned a compilation error.

undefined:1
[{"text":"some text and then % sign and then, again % sign","link":"another text with %"}]^

SyntaxError: Unexpected token % in JSON at position 30at JSON.parse (<anonymous>)at Object.<anonymous> (/tmp/bRVTxjVcfu.js:62:15)at Module._compile (internal/modules/cjs/loader.js:778:30)at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)at Module.load (internal/modules/cjs/loader.js:653:32)at tryModuleLoad (internal/modules/cjs/loader.js:593:12)at Function.Module._load (internal/modules/cjs/loader.js:585:3)at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)at startup (internal/bootstrap/node.js:283:19)at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

Answer №1

You can simply cut and reconnect:

const parsedTemp = temp.map(tempItem => Object.entries(tempItem)
  .reduce((acc, [key, value]) =>
    ({...acc, [key]: value.split('%').join('\\%')}), {})
)

Note: I have not yet verified for any errors, but the logic seems to be correct.

UPDATE: I overlooked the necessity of escaping the backslash - It will display as '\\%' in your string, which is accurate.

Answer №2

let data = [{
  info: 'this is some example text with % sign and another % sign',
  reference: 'more text including % symbol'
}, ];

for (const item of data) {
  for (const property in item) {
    item[property] = item[property].replace(/%/g, String.raw`\%`)
  }
}

console.log(data)

Answer №3

To accomplish this task, you can iterate through the `temp` array using the `Array.forEach()` method and then utilize `Object.keys()` to replace a substring within the entire string by employing the `String.replaceAll()` function.

Check out the demonstration below:

var temp = [
  {
    text:'some text and then % sign and then, again % sign',
    link: 'another text with %'
  }
];

temp.forEach(obj => {
  Object.keys(obj).forEach(key => {
    obj[key] = obj[key].replaceAll('%', '\\%')
  })
});

console.log(temp);

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

Locating a specific item using its individual ID within Firebase

One thing that's often overlooked in Firebase tutorials is how to retrieve objects based on their unique IDs. The push() method generates these unique IDs automatically, but the question remains: how do we access the specific object associated with an ...

I encountered an issue where my MongoDB connection appeared to hang indefinitely, eventually leading to a disconnected error message

After spending a week trying to troubleshoot this issue, I am reaching out for help. Initially, my code was working seamlessly but suddenly it has stopped functioning. The goal is to connect my Vue app to a MongoDB hosted by a third party using the followi ...

Count the number of times an iteration occurs in AngularJS/JavaScript

I need assistance with my code snippet below, as I am trying to determine the count of all instances where $scope.rm is equal to "failed" or when $scope.percentage is less than 50. angular.forEach(result1, function (value, key) { $scope.percentage ...

Determining the equation from a string and converting it to an integer

I'm working with a table that contains formulas. For example, the formula is: (GP1/(GP1 + GP2))*100%. For my code using jQuery, I need to replace GP1 with the value from textbox1, GP2 with the value from textbox2, and remove the % symbol. My attemp ...

What is the process for configuring environment variables in a React application?

I have set up my React app to run on http://localhost:3000, and now I am looking to configure environment variables for different environments such as development, production, staging, and local. These are the URLs for my React app in various environments ...

best method to pass byte array to ListBlockingQueue

Given that I am handling an array of bytes passed to me, not by choice but out of necessity. My task is to transfer the data to a LinkedBlockingQueue and ultimately iterate through the bytes to construct one or multiple XML messages (which may potentially ...

Implementing Formik in React for automatic updates to a Material-UI TextField when blurred

Presently, I am developing a dynamic table where users can simultaneously modify multiple user details in bulk (Refer to the Image). The implementation involves utilizing Material-UI's <TextField/> component along with Formik for managing form s ...

What is the best way to divide text into key-value pairs using JavaScript?

I have data in text format from my Raspberry Pi that I need to insert into MongoDB as key-pair values or JSON for my Node.js Application. I'm relatively new to JavaScript and I'm looking for a solution. Any suggestions would be greatly appreciate ...

Troubleshooting a glitch with passing a variable to a PHP script using AJAX

Explanation of the page functionality: When the quiz php page loads, a user can create a score using a function in quiz.js. This score is then stored in a variable score within quiz.js Once the score is generated, the user must click a button to move on ...

Array with multiple dimensions using commas as delimiters

My array (array[]) contains elements in the format below, separated by a comma: array[0] = abc, def, 123, ghi I want to transform this array into another multi-dimensional array (arrayTwo[]), structured like this: arrayTwo[0][0] = "abc" arrayTwo[0][1] = ...

Organically organize search outcomes within an object through a fs directory traversal

Scanning multiple translation files within a file directory and transferring the data to a global object for easy retrieval of translations with i18nContent.messages.en.9999 This is how the file tree is structured: locales messages en.json =& ...

What could possibly prevent Jasmine Spyon from being named?

I am currently facing an issue with a failing test even though I have included the necessary calls. One specific area where I am encountering this problem is with the PrimeNG Message Service that I am spying on. Below, you can find the code snippet that I ...

What is the best way to save an array of integers as bytes in a file using Ruby?

I am attempting to write a binary string array representation to a file, but encountering issues. #str is a String not an Array str = "[80, 75, 3, 4, 10, 0, 0, 0, 0, 0, -74, 121, 57, 64, 0, 0, 0, 0]" File.open('/Users/file.zip', "wb") do |file| ...

The Angular Material dialog fails to display content when triggered within an event listener in Google Maps

Within my project, I am utilizing Angular 6.0.6 and Angular Material 6.3.0. One issue I have encountered is with a dialog component that I have added to the entryComponents in the app module. Strangely, when I attempt to open this dialog within the rightcl ...

Neglecting to review the CSS - embracing ejs layouts in Express

I am encountering an issue with the express ejs layouts where only the mainPage is able to read the CSS, while the other pages are unable to do so (even though the HTML reads it). Additionally, if I want to use another layout such as "layout2.ejs", what s ...

Achieving the equivalent of php crypt() in NODE.JS

Can anyone assist with converting PHP to JavaScript (Node.js)? $key = crypt($key, $salt); I am currently in the process of rewriting a PHP script using Node.js, and I have encountered an issue with generating hash signatures similar to the ones created b ...

Is it possible to normalize and regulate a four-dimensional array using a three-dimensional mask?

import numpy as np ts = np.random.rand(40,45,40,1000) mask = np.random.randint(2, size=(40,45,40),dtype=bool) #creating a masked array ts_m = np.ma.array(ts, mask=ts*~mask[:,:,:,np.newaxis]) #demeaning ts_md = ts_m - ts_m.mean(axis=3)[:,:,:,np.newaxis] # ...

Async/Await mishap

Could someone please explain why the code below is printing a blank result? I was expecting it to print "done" since I thought the await keyword would make the program wait for the promise to be resolved. Appreciate any help provided! let message = &apos ...

Load as soon as the browser is launched

I have developed a unique button that utilizes JavaScript to display the server status through an API. However, I am facing an issue where the server status does not automatically load when the browser is opened for the first time. You need to manually cli ...

Modify the background hue of the added tr element

When adding rows to a table, I have a condition to check if the current date and time fall within the range specified by the start and end date and times of each row. If this condition is met, I need to update the background color of the row. $('# ...