Home > Back-end >  How do I remove a span tag in a string with Javascript?
How do I remove a span tag in a string with Javascript?

Time:10-08

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!

CodePudding user response:

You can use DOM parser for that

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

const parser = new DOMParser();
const parsed = parser.parseFromString(str, "text/html");
parsed.querySelector("span").remove();
console.log(parsed.body.innerHTML);

CodePudding user response:

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()

  • Related