Search code examples
javascriptarraysreplacejavascript-objectsreplaceall

How can I replace a substring with some other substring in the values of objects of an array in Javascript?


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

I want to replace all % signs with \% in the temp array of objects. How can I do it?

Desired Output:

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

I've tried these two ways, but, none of them worked:

First one is 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: It resulted in two backslashes.

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

Second way is using JSON.parse and JSON.stringify:

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

Output: 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)

Solution

  • Could just slit and rejoin:

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

    Disclaimer - haven't tested for errors but logic is sound

    EDIT: I forgot you need to escape the backslash - It will appear as '\\%' in your string, but that is correct.