【问题标题】:How can I replace a substring with some other substring in the values of objects of an array in Javascript?如何在 Javascript 中用数组对象的值中的其他子字符串替换子字符串?
【发布时间】: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


【解决方案1】:

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)

【讨论】:

  • 它导致两个反斜杠。尝试运行代码
  • 我知道,用一个反斜杠创建一个字符串是不可能的
【解决方案2】:

可以切开并重新加入:

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

免责声明 - 尚未测试错误但逻辑合理

【讨论】:

  • 当我在控制台记录 parsedTemp 时,它显示 [ undefined ]。此外,您在 .reduce 中缺少一个大括号
猜你喜欢
  • 1970-01-01
  • 2019-11-21
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多