Search code examples
javascriptregexreplaceall

Replace tags with new tags with innerHTML to set to id


I have the following text:

Send to <a class="tipo9" id="1">Example Mark</a> and <a class="tipo0" id="3">Testing James</a> a new Document

And would like to obtain the following code:

Send to <per>1</per> and <per>3</per> a new Document

The number between the tags is the id number.

I have found a very complicated solution like:

function convert(f) {
    var str=f;
    str=str.replaceAll('<a class="', '[per]');
    str=str.replaceAll('/a>', '[/per]');
    str=str.replaceAll(/tipo\d/g, '');
    str=str.replaceAll(/['"]+/g, '');
    str=str.replaceAll('"', '');
    str=str.replaceAll(' id=', '');
    str=str.replaceAll(/\s*\>.*?\<\s*/g, "")
    str=str.replaceAll('[per]', '<per>');
    str=str.replaceAll('[/per]', '</per>');
    str=str.trim();
    document.getElementById('testoHTML').value=str;
}

but it gives different problems. I know that it should exist another solution with regex but I was not able to obtain a working result.

Hope to find some good solution :)


Solution

  • This seems more like a job for DOMParser:

    var parsed = new DOMParser().parseFromString('Send to <a class="tipo9" id="1">Example Mark</a> and <a class="tipo0" id="3">Testing James</a> a new Document', "text/html");
    parsed.querySelectorAll("a").forEach(e=>{
      n = document.createElement("pre");
      n.innerHTML  = e.id;
      e.replaceWith(n);
    })
    var result = parsed.body.innerHTML;
    console.log(result);