1

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!

1
  • 2
    Well I wouldn't do it using regex (since you've tagged that). It's JS, so use DOM functions. Commented Oct 7, 2022 at 13:07

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.