如何使用 "for" 和字符串替换?

How to use "for" along with string replace?

我想在同一个字符串中进行多次替换。我有这个:

ignoredids = [{"ignoredid":"3329"},{"ignoredid":"25895"}];
userlist = `<div id="u343">something</div><div id="u3143">something</div><div id="u25895">something</div><div id="u5343">something</div><div id="u3329">something</div>`;

替换后应该如下所示:

<div id="u343">something</div><div id="u3143">something</div><div id="u25895">ignore this</div><div id="u5343">something</div><div id="u3329">ignore this</div>

所以我尝试了:

for (let { ignoredid } of ignoredids) {
  mylist = userlist.replace(`<div id="u${ignoredid}">something</div>`,`<div id="u${ignoredid}">ignore this</div>`);        
} 

但它似乎没有做任何事情。怎么了?

按照你现在的写法,它只会替换最后一个 id 并将其分配给 mylist 变量,因为 .replace 不会改变字符串。

如果我们分配给 userlist 而不是 mylist 它将按照您希望的方式工作,因为这样我们实际上是在每次迭代中修改字符串:

ignoredids = [{"ignoredid": "3329"}, {"ignoredid": "25895"}];
userlist = `<div id="u343">something</div><div id="u3143">something</div><div id="u25895">something</div><div id="u5343">something</div><div id="u3329">something</div>`;

for (let { ignoredid} of ignoredids) {
  userlist = userlist.replace(`<div id="u${ignoredid}">something</div>`, `<div id="u${ignoredid}">ignore this</div>`);
}

document.getElementById("myDiv").innerHTML = userlist;
<div id="myDiv"></div>

  • 创建仅包含“u”前缀 ID 的数组
  • 不要将 replace() 与硬编码内容一起使用。
  • 而且由于正则表达式不应该用在 HTML 类似的字符串上 - 改用适当的 DOM 解析器或内存元素 。了解 DOMParser.parseFromString()

// Helper function
const arrHas = (arr, val) => arr.some(a => val === a);

// Your stuff:
const replacer = "IGNORE THIS";
const ignoredids = [
  {"ignoredid":"3329"},
  {"ignoredid":"25895"},
];
const userlist = `<div id="u343">Lorem ipsum</div>
<div id="u3143">Dolor sit amet</div>
<div id="u25895">consectetur adipisicing</div>
<div id="u5343">Elit enim </div>
<div id="u3329">Nemo eveniet</div>`;

// Create an Array of "u" prefixed IDs 
const uIDs = ignoredids.map(o => `u${o.ignoredid}`); 

// Use DOMParser!!
const DOC = new DOMParser().parseFromString(userlist, "text/html");

[...DOC.body.children].forEach(EL => {
  if (arrHas(uIDs, EL.id)) EL.textContent = replacer;
});

const result = DOC.body.innerHTML;
console.log(result)

result 现在是这个 HTML-like 字符串:

<div id="u343">Lorem ipsum</div>
<div id="u3143">Dolor sit amet</div>
<div id="u25895">IGNORE THIS</div>
<div id="u5343">Elit enim </div>
<div id="u3329">IGNORE THIS</div>