繁体   English   中英

在 html 标签之间查找和替换内容

[英]Find and Replace contents in between html tags

我有类似这样的 JSON 数据。

productMessages: [
  {
    'errorOccurred': true,
    'message': 'Nicht mehr verfügbarrer Auslaufartike <articleNo>32210544030</articleNo> der Vorrat reicht <articleNo>32210544031</articleNo>',
    'productCode': '2222222222',
    'quantity': 3.0,
    'type': 'ERROR'
  },
]

In the message key, now I want to replace articleNo 10107030 and 10107030 with URL parameters something like this https://example.some.com/locale/locale/products/32210544030.html https://example.some.com/locale /locale/products/32210544031.html

商品编号(32210544030 和 32210544031)具有 append 和 URL 参数。

我做了一些东西,但只为一篇文章工作没有标签。 如果我在响应中有多个 articleNo 标记,则它不起作用。

let match = message.match("<articleNo>(.*?)</articleNo>"); // find article number tag
if (match) {
  // Create URL
  // window.app.props.url.adp = 'https://example.some.com/locale/locale/products/{productId}.html';
  const url = window.app.props.url.adp.replace('{productId}', match[1]);
  const newMessage = message.replace('<articleNo>', `<a href='${url}'>`).replace('</articleNo>', '</a>');
  return newMessage;
}

我试过 replaceAll 和 matchAll 没有运气。

谢谢提前。

在处理标记时,通常最好应用适当的解析而不是正则表达式方法。 在下面的代码片段中,我创建了一个<div>作为临时容器,然后我可以在其中使用 DOM 方法处理articleno元素:

 productMessages=[ { 'errorOccurred': true, 'message': 'Nicht mehr verfügbarer Auslaufartikel <articleNo>32210544030</articleNo> der Vorrat reicht <articleNo>32210544031</articleNo>', 'productCode': '2222222222', 'quantity': 3.0, 'type': 'ERROR' } ]; function addLinks(msg){ const d=document.createElement("div"); d.innerHTML=msg; d.querySelectorAll("articleno").forEach(a=>a.innerHTML="https://example.some.com/locale/locale/products/"+a.innerHTML+".html"); return d.innerHTML; } productMessages.forEach(pm=>pm.message=addLinks(pm.message)); console.log(productMessages);

使用replaceAll

/**
* @type {String}
*/
let message = "Nicht mehr verfügbarrer Auslaufartike <articleNo>32210544030</articleNo> der Vorrat reicht <articleNo>32210544031</articleNo>";

let str = message.replaceAll(/<articleNo>(.*?)<\/articleNo>/g, function (match, id) {
    let anchor = `<a href = "https://myproductsite.com/products/${id}" ></a>`;
    return anchor;
});

console.log(str);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM