【问题标题】:Find and Replace contents in between html tags查找和替换 html 标签之间的内容
【发布时间】:2022-01-06 22:15:21
【问题描述】:

我有类似这样的 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'
  },
]

在消息键中,现在我想用类似 https://example.some.com/locale/locale/products/32210544030.html 的 URL 参数替换 articleNo 10107030 和 10107030 https://example.some.com/locale/locale/products/32210544031.html

文章编号(32210544030 和 32210544031)必须附加 URL 参数。

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

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 没有运气。

谢谢提前。

【问题讨论】:

标签: javascript html regex javascript-objects


【解决方案1】:

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

const 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'
  }
];
app={props:{url:{adp:'https://example.some.com/locale/locale/products/{productId}.html'}}};

function addLinks(msg){
 const d=document.createElement("div");
 d.innerHTML=msg;
 d.querySelectorAll("articleno").forEach(a=>a.innerHTML=app.props.url.adp.replace("{productId}",a.innerHTML));
 return d.innerHTML;
}

productMessages.forEach(pm=>pm.message=addLinks(pm.message));

console.log(productMessages);

【讨论】:

    【解决方案2】:

    使用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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-31
      • 1970-01-01
      • 1970-01-01
      • 2010-10-01
      • 1970-01-01
      • 2014-09-29
      相关资源
      最近更新 更多