【发布时间】:2022-11-16 07:13:14
【问题描述】:
var temp = [
{
text:'some text and then % sign and then, again % sign',
link: 'another text with %',
},
];
我想用 temp 对象数组中的 \% 替换所有 % 符号。我该怎么做?
期望的输出:
var temp = [
{
text:'some text and then \% sign and then, again \% sign',
link: 'another text with \%',
},
];
我已经尝试了这两种方法,但是,它们都不起作用:
第一个是使用 for 循环:
for(let i = 0; i<temp.length; i++) {
temp[i].text = temp[i].text.replace(/%/g, '\\%');
temp[i].link = temp[i].link.replace(/%/g, '\\%');
}
输出:它导致了两个反斜杠。
[
{
text: 'some text and then \\% sign and then, again \\% sign',
link: 'another text with \\%'
}
]
第二种方法是使用 JSON.parse 和 JSON.stringify:
temp = JSON.parse(
JSON.stringify(temp).replace(/%/g, '\\%')
);
输出:编译错误
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)
【问题讨论】:
-
\ 需要在字符串中进行转义,因此 \\% 的结果是正确的,计算结果为 \%
-
是的,但我该怎么做呢?
标签: javascript arrays replace javascript-objects replaceall