1

I have some string with html tags.

var str = '<a href="www.com">text</a>
<script>
//some code etc
</script>
............... etc
';

I need to remove <script>....</script> using regexp with js's replace() function. Could not figure how to do it.

My efforts were:

/(<script).(</script>)/m 
/<script.*>([\s\S]*)</script>/m
/(<script)*(</script>)/
/<script*</script>/

no success =(

2 Answers 2

2

Try...

/<script>[\s\S]*<\/script>/

If this is for arbitrary HTML, consider using DOM manipulation methods instead.

var fauxDocumentFragment = document.createElement("div");

fauxDocumentFragment.innerHTML = str;

var scriptElements = fauxDocumentFragment.getElementsByTagName("script");

while (scriptElements.length) {
    scriptElements[0].parentNode.removeChild(scriptElements[0]);
}

If you're lucky enough to only have to support the newer browsers, go with...

var fauxDocumentFragment = document.createElement("div");

fauxDocumentFragment.innerHTML = str;

[].forEach(fauxDocumentFragment.querySelectorAll("script"), function(script)
    script.parentNode.removeChild(script);
});
Sign up to request clarification or add additional context in comments.

Comments

1

You can try the following:

str.replace(/<script.*?>.*?<\/script>/m, "");

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.