You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript数组对象的属性值中替换子字符串

如何将数组对象中的%替换为%?

原始数据:

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)

解决方案

关于方法一的说明

你看到的\\%是控制台的转义显示,实际字符串中已经是单个\%。可以直接打印字符串内容验证:

console.log(temp[0].text);
// 输出:some text and then \% sign and then, again \% sign

如果需要更通用的处理(比如对象有更多字符串属性),可以用遍历所有属性的方式:

temp.forEach(item => {
  Object.keys(item).forEach(key => {
    if (typeof item[key] === 'string') {
      item[key] = item[key].replace(/%/g, '\\%');
    }
  });
});

修复方法二的错误

方法二报错是因为JSON字符串中的反斜杠需要转义。要让JSON.parse后得到\%,替换时需要把%换成\\\\%(JSON字符串里两个反斜杠解析后对应一个):

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

这样处理后,数组对象中的字符串就会正确替换为\%。

内容的提问来源于stack exchange,提问作者Govind Tomar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 17:55:30