Home > Software engineering >  Find and Replace contents in between html tags
Find and Replace contents in between html tags

Time:11-30

I have JSON data something like this.

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

Article number(32210544030 and 32210544031) has to append with the URL parameter.

I have done some stuffs but is is only working for one articleNo tag. It is not working if I have multiple articleNo tags in the response.

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;
}

I have tried replaceAll and matchAll no luck.

Thanks Advance.

CodePudding user response:

When dealing with markup it is usually better to a apply proper parsing instead of regular expression methods. In the following snippet I created a <div> as a temporary container in which I could then use DOM methods to work on the articleno elements:

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);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Use 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);
  • Related