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)