Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I remove a span tag in a string with Javascript?

Let’s say I have this string (which is a string consisting of html tags):

const str = "<li class='test'>
    <div class='myDiv' >
    <span class='myClass'>Person is a: </span>
    <a class='myLink' tabindex='0'> Great citizen. Really nice guy</a>
    </div>
    </li>"

How would I remove the <span> tags along with everything in between them, so the output is the following:

const str = "<li class='test'>
    <div class='myDiv' >
    <a class='myLink' tabindex='0'> Great citizen. Really nice guy</a>
    </div>
    </li>"

Thanks for your help!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

let str = `<li class='test'>
    <div class='myDiv' >
    <span class='myClass'>Person is a: </span>
    <a class='myLink' tabindex='0'> Great citizen. Really nice guy</a>
    </div>
    </li>`;

const reg = new RegExp("<span(.*?)span>", "gms");
console.log(str.replace(reg, ""));

//if DOM then->
// document.querySelector('.myClass').remove()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading