Jiew Meng
Jiew Meng

Reputation: 88197

How do i strip whole script sections with Javascript

if i have a string like

<p>this is some content</p><script>alert('hello');</script>

i want to get the string without any scripts, but with the formatting, how do i do it?

<p>this is some content</p>

i tried

var html = "<p>etc</p><script>alert('hello world');</script>".replace("<script*</script>", "p");

but that gave me something like

".replace("", "p"); $('#blogDescription').html(html); }); }); 

Upvotes: 0

Views: 222

Answers (3)

chris.rickard
chris.rickard

Reputation: 1035

var html = "<p>etc</p><script>alert('hello world');</script>".replace("<script>").replace("</script>");

Upvotes: 0

Yi Jiang
Yi Jiang

Reputation: 50105

You can do this without using regex, by using some DOM manipulation you can run through each of the elements in the DOM fragment created from the string and remove the script tags.

var html = "<p>etc</p><script>alert('hello world');</script>";

var container = document.createElement('div');
container.innerHTML = html;

function stripScript(parent){
  var elements = parent.children;

  for(var i = 0; i < elements.length; i++){
    if(elements[i].nodeName === 'SCRIPT'){
      parent.removeChild(elements[i]);
    } else if(elements[i].children.length > 0){
      stripScript(elements[i]);
    }
  }
}

stripScript(container);

console.log(container.innerHTML);

Or with jQuery

var html = "<p>etc</p><script>alert('hello world');</script>";

container = document.createElement('div');
container.innerHTML = html;
$(container).find('script').remove();

console.log(container.innerHTML);

Upvotes: 2

Vinay B R
Vinay B R

Reputation: 8421

try using this

/<script\b[^>]*>(.*?)<\/script>/i

Upvotes: 0

Related Questions