Reputation: 103
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)
Upvotes: 3
Views: 449
Reputation: 27232
You can simply achieve this by iterating the temp
array with the help of Array.forEach()
and then by using Object.keys()
you can replace the sub string of the whole string by using String.replaceAll()
method.
Live Demo :
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);
Upvotes: 0
Reputation: 1447
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.
Upvotes: 2
Reputation: 24681
const temp = [{
text: 'some text and then % sign and then, again % sign',
link: 'another text with %',
}, ];
for (const obj of temp) {
for (const key in obj) {
obj[key] = obj[key].replace(/%/g, String.raw`\%`)
}
}
console.log(temp)
Upvotes: 0